0
def isim():
    fh = open('hash.txt')
    for line in fh:
        if re.search('Unique description', line):
            print(line, end='')
def main():
    isim()

if __name__ == "__main__": main()

我的问题是如何读取目录中的所有文本文件而不是 hash.txt

4

2 回答 2

3

使用 glob 模块。

import re
import glob
def isim():
    textfiles = glob.glob(r"C:\mydir\*.txt")
    for fh in textfiles:
        for line in open(fh):
            if re.search('Unique description', line):
                print(line, end='')
def main():
    isim()

if __name__ == "__main__": main()
于 2013-04-03T14:17:23.680 回答
1

用于os.listdir()列出目录的内容;然后,您可以根据需要添加一个简单的文件名过滤器:

path = '/some/directory'
for filename in os.listdir(path):
    if not filename.endswith('.txt'):
        continue
    filename = os.path.join(path, filename)
    with open(filename, 'r') as fh:
        for line in fh:
            if re.search('Unique description', line):
                print(line, end='')
于 2013-04-03T14:16:37.590 回答