user110327 user110327 - 4 years ago 110
Python Question

How to open multiple files in Python by following a text list of filenames?

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:

def main():
text_file = open("filename.txt","r")
#operations
text_file.close()

main()

Answer Source

Use 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download