0

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()
  • Possible duplicate of [Find all files in directory with extension .txt in Python](http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python) – Darrick Herwehe Feb 06 '17 at 14:15

2 Answers2

2

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.

Community
  • 1
  • 1
Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • 1
    btw. using a `with` statement instead of manually closing the file would probably be more pythonic and safe. – languitar Feb 06 '17 at 11:41
-1

not sure how many files you have but you could also look at http://www.dabeaz.com/generators-uk/genfind.py and then send this to http://www.dabeaz.com/generators-uk/genopen.py

this is the ideal solution for processing a lot of data.. Thanks Dave ;-)

vtk
  • 1