I have a Python code to perform some operations on a text file. I need to run this code over around 200+ text files that are all stored in the same folder.
I want the code to open one text file at a time, perform the operations and then start over with the next text file.
Can you give me some pointers regarding how I can do this?
My code is like this:
text_file = open("filename.txt","r")
listdir to iterate through files.
import os def main(): for filename in os.listdir(somedir): filepath = os.path.join(somedir, filename) if os.path.isfile(filepath): # Is filepath really a file, not a directory? text_file = open(filepath,"r") #operations text_file.close() main()
As noted in the comments, it's better to use with.