Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading