pythonstringfunction

write a function words_from_file(filename1,filename2) that splits the text from a file into words and writes these one word per line to a new file


Im not able to fully test the code, I run the code and I do not get any errors, but not sure does it actually reads a file and then writes each word on the next line onto another file.

This is my code, tell me what you think.

def words_from_file(filename1,filename2):
    try:
        with open(filename1,'r') as f:
            for lines in f:
                with open(filename2, 'w') as g:
                    for word in lines:
                        g.writelines(word)
    except:
        print("Error: File not found")

Solution

  • You mentioned that: "writes each word on the next line onto another file". The following code reads from the input file and writes to another file word by word.

    Code:

    def words_from_file(filename1, filename2):
        try:
            with open(filename1, 'r') as f:
                with open(filename2, 'w') as g:
                    for line in f:
                        words = line.split()
                        for word in words:
                            g.write(word + '\n')
        except FileNotFoundError:
            print("Error: File not found")
    

    Output:

    It
    is
    a
    sample
    file.