Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

python - Open file by filename wildcard

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:ext*.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:extsomefile.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:ircas*.txt"
txt = glob.glob(filepath)

lines = string.split(txt, '
') #AttributeError: 'list' object has no attribute 'split'
print lines
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import os
import re
path = "/home/mypath"
for filename in os.listdir(path):
    if re.match("textd+.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,

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...