通过文件名通配符打开文件
我有一个文件夹,里面全是以 .txt
结尾的文本文件。我的目标是打印这些文本文件的内容。我希望能用通配符 *.txt
来指定我想打开的文件名(我在想类似 F:\text\*.txt
这样的方式),然后把文本文件的每一行分开,最后打印出来。
这里有个我想做的例子,但我希望在执行命令时能更改 somefile
的内容。
f = open('F:\text\somefile.txt', 'r')
for line in f:
print line,
我之前查过 glob 模块,但我搞不清楚怎么对文件做任何操作。这里是我想到的,但没有成功。
filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)
lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines
5 个回答
6
这段代码解决了最初问题中的两个方面:它会在当前文件夹里查找.txt文件,然后允许用户用正则表达式搜索某些内容。
#! /usr/bin/python3
# regex search.py - opens all .txt files in a folder and searches for any line
# that matches a user-supplied regular expression
import re, os
def search(regex, txt):
searchRegex = re.compile(regex, re.I)
result = searchRegex.findall(txt)
print(result)
user_search = input('Enter the regular expression\n')
path = os.getcwd()
folder = os.listdir(path)
for file in folder:
if file.endswith('.txt'):
print(os.path.join(path, file))
txtfile = open(os.path.join(path, file), 'r+')
msg = txtfile.read()
search(user_search, msg)
17
你可以使用glob模块来获取符合通配符的文件列表:
然后你只需要对这个列表进行一个循环,就完成了:
filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)
for textfile in txt:
f = open(textfile, 'r') #Maybe you need a os.joinpath here, see Uku Loskit's answer, I don't have a python interpreter at hand
for line in f:
print line,
64
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,
import glob
path = "/home/mydir/*.txt"
for filename in glob.glob(path):
with open(filename, 'r') as f:
for line in f:
print line,
虽然你忽略了我这个很好的解决方案,但我还是给你提供一下: