Open file by filename wildcard

greg picture greg · Feb 16, 2011 · Viewed 73.8k times · Source

I have a directory of text files that all have the extension .txt. My goal is to print the contents of the text file. I wish to be able use the wildcard *.txt to specify the file name I wish to open (I'm thinking along the lines of something like F:\text\*.txt?), split the lines of the text file, then print the output.

Here is an example of what I want to do, but I want to be able to change somefile when executing my command.

f = open('F:\text\somefile.txt', 'r')
for line in f:
    print line,

I had checked out the glob module earlier, but I couldn't figure out how to actually do anything to the files. Here is what I came up with, not working.

filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)

lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines

Answer

Uku Loskit picture Uku Loskit · Feb 16, 2011
import os
import re
path = "/home/mypath"
for filename in os.listdir(path):
    if re.match("text\d+.txt", filename):
        with open(os.path.join(path, filename), 'r') as f:
            for line in f:
                print line,

Although you ignored my perfectly fine solution, here you go:

import glob
path = "/home/mydir/*.txt"
for filename in glob.glob(path):
    with open(filename, 'r') as f:
        for line in f:
            print line,