按文件名通配符打开文件 [英] Open file by filename wildcard
问题描述
我有一个文本文件目录,所有文件的扩展名都为.txt
.我的目标是打印文本文件的内容.我希望能够使用通配符*.txt
指定要打开的文件名(我正在考虑类似F:\text\*.txt
这样的行?),分割文本文件的行,然后打印输出.
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.
这是我要执行的操作的一个示例,但是我希望能够在执行命令时更改somefile
.
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,
我之前已经签出了glob模块,但是我不知道如何对文件做任何实际的事情.这是我想出的,不起作用.
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
推荐答案
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,
这篇关于按文件名通配符打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!