扫描几个文本文件

时间:2014-04-07 07:43:54

标签: python file text

我使用的是python 2.7,我有一个包含多个文本文件的目录。

基本上文件名称相同,最后是1XX的计数器。我想在文本文件中搜索特定字符串并将其写入不同的文件。但是,如果我将所有文件放在一个文本文件中,我只知道如何做到这一点。

我想扫描目录中的每个文本文件,如果找到我的字符串,我想将其放入例如result.txt并注意我在哪个文件中找到它,当然还有特定的字符串。

有人知道该怎么做吗?

谢谢!

1 个答案:

答案 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()
相关问题