Skip to content Skip to sidebar Skip to footer

Python - Need To Loop Through Directories Looking For Txt Files

I am a total Python Newb I need to loop through a directory looking for .txt files, and then read and process them individually. I would like to set this up so that whatever direc

Solution 1:

import os, fnmatch

def findFiles (path, filter):
    for root, dirs, files inos.walk(path):
        for file in fnmatch.filter(files, filter):
            yieldos.path.join(root, file)

Use it like this, and it will find all text files somewhere within the given path (recursively):

for textFile in findFiles(r'C:\Users\poke\Documents', '*.txt'):
    print(textFile)

Solution 2:

os.listdir expects a directory as input. So, to get the directory in which the script resides use:

scrptPth = os.path.dirname(os.path.realpath(__file__))

Also, os.listdir returns just the filenames, not the full path. So open(file) will not work unless the current working directory happens to be the directory where the script resides. To fix this, use os.path.join:

import os

scrptPth = os.path.dirname(os.path.realpath(__file__))

for file inos.listdir(scrptPth):
    with open(os.path.join(scrptPth, file)) as f:

Finally, if you want to recurse through subdirectories, use os.walk:

import os

scrptPth = os.path.dirname(os.path.realpath(__file__))

for root, dirs, files inos.walk(scrptPth):
    for filename in files:
        filename = os.path.join(root, filename)
        with open(filename, 'r') as f:
            head,sub,auth = [f.readline().strip() for i in range(3)]
            data=f.read()
            #data.encode('utf-8')

Post a Comment for "Python - Need To Loop Through Directories Looking For Txt Files"