.write() is only writing to output file in the last iteration of a loop

Question:

I’m trying to open a bunch of files in a directory, remove some words from those files and write the output to a file in the same directory. I’m having problems when trying to write to the output file. There isn’t anything being written to the file. How can I fix this?

Here is my code:

path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'

for root, dir, files in os.walk(path):
    for file in files:
        os.chdir(path)
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open(output, 'w') as output_file:
                output_file.write(x)
Asked By: Fordo

||

Answers:

You are erasing the content of the file each time you open it with the 'w' mode in the loop. So, the way your code is, you are not going to see anything in the file if your last loop iteration produces an empty result.

Change the mode to 'w+' or 'a':

        with open(output, 'w+') as output_file:

Reading and Writing Files:

mode can be ‘r’ when the file will only be read, ‘w’ for only writing (an existing file with the same name will be erased), and ‘a’ opens the file for appending;

Answered By: olivecoder
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.