Skip to content
Advertisement

Python: Counting words from a directory of txt files and writing word counts to a separate txt file

New to Python and I’m trying to count the words in a directory of text files and write the output to a separate text file. However, I want to specify conditions. So if word count is > 0 is would like to write the count and file path to one file and if the count is == 0. I would like to write the count and file path to a separate file. Below is my code so far. I think I’m close, but I’m hung up on how to do the conditions and separate files. Thanks.

JavaScript

Advertisement

Answer

I would strongly urge you to not repurpose stdout for writing data to a file as part of the normal course of your program. I also wonder how you can ever have a word “count < 0”. I assume you meant “count == 0”.

The main problem that your code has is in this line:

JavaScript

The string constant "path" I’m pretty sure doesn’t belong there. I think you want filepath there instead. I would think that this problem would prevent your code from working at all.

Here’s a version of your code where I fixed these issues and added the logic to write to two different output files based on the count:

JavaScript

Result:

file seen.txt:

JavaScript

file missing.txt:

JavaScript

(excuse me for using some search words that were a bit more interesting than yours)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement