0

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) 
4
  • On which Files You Are performing operation like text Commented Feb 28, 2019 at 10:52
  • Assuming output is your output file, with open(output, 'w') as output_file: Commented Feb 28, 2019 at 10:53
  • 1
    Maybe you are expecting to write to C:/Users/User/Desktop/filter_mini_mouse/mouse but in your open statement, you're writing to a file named out. Commented Feb 28, 2019 at 10:53
  • You guys are right I actually want to write the output to 'C:/Users/User/Desktop/filter_mini_mouse/mouse' i.e output as I've named it. I'm still getting the same problem, however, The file is being created but there is nothing in it. Commented Feb 28, 2019 at 11:13

1 Answer 1

3

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;

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Using 'a' worked for me! Thank you again!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.