我使用的是python 2.7,我有一个包含多个文本文件的目录。
基本上文件名称相同,最后是1
到XX
的计数器。我想在文本文件中搜索特定字符串并将其写入不同的文件。但是,如果我将所有文件放在一个文本文件中,我只知道如何做到这一点。
我想扫描目录中的每个文本文件,如果找到我的字符串,我想将其放入例如result.txt
并注意我在哪个文件中找到它,当然还有特定的字符串。
有人知道该怎么做吗?
谢谢!
答案 0 :(得分:0)
import os
files = os.listdir('.')
newfile = 'myfile.txt'
mystring = 'mystring'
found = []
for f in files:
myfile = open(f, 'r')
if mystring in myfile.read():
found.append(f)
myfile.close()
myfile = open(newfile, 'w')
myfile.write("\n".join(found))
myfile.close()