我有一个文件夹,里面有很多文本文件(EPA10.txt、EPA55.txt、EPA120.txt...、EPA150.txt)。我在每个文件中有两个要搜索的字符串,搜索结果写在一个文本文件result.txt中。到目前为止,我已经将其用于单个文件。以下是工作代码:
if 'LZY_201_335_R10A01' and 'LZY_201_186_R5U01' in open('C:\\Temp\\lamip\\EPA150.txt').read():
with open("C:\\Temp\\lamip\\result.txt", "w") as f:
f.write('Current MW in node is EPA150')
else:
with open("C:\\Temp\\lamip\\result.txt", "w") as f:
f.write('NOT EPA150')现在,我希望对文件夹中的所有文本文件重复此操作。请帮帮忙。
发布于 2015-01-16 18:27:39
假设您有一些文件的名称从EPA1.txt到EPA150.txt,但是您不知道所有的名称,您可以将它们完全放在一个文件夹中,然后使用os.listdir()方法读取该文件夹中的所有文件,以获得文件名列表。您可以使用listdir("C:/Temp/lamip")读取文件名。
另外,您的if语句是错误的,您应该这样做:
text = file.read()
if "string1" in text and "string2" in text代码如下:
from os import listdir
with open("C:/Temp/lamip/result.txt", "w") as f:
for filename in listdir("C:/Temp/lamip"):
with open('C:/Temp/lamip/' + filename) as currentFile:
text = currentFile.read()
if ('LZY_201_335_R10A01' in text) and ('LZY_201_186_R5U01' in text):
f.write('Current MW in node is ' + filename[:-4] + '\n')
else:
f.write('NOT ' + filename[:-4] + '\n')PS:你可以在你的路径中使用/代替\\,Python会自动为你转换它们。
发布于 2015-01-16 19:43:51
模块化!模块化!
当然,并不是说必须编写不同的Python模块,而是要隔离手头的不同任务。
这些任务中的每一个都可以独立解决。也就是说,要列出文件,您可能需要过滤os.listdir。
对于步骤2,您要搜索的文件是1个还是1,000个并不重要。例程是一样的。您只需迭代步骤1中找到的每个文件。这表明步骤2可以实现为一个函数,该函数以文件名(和可能的搜索字符串)作为参数,并返回True或False。
步骤3是步骤1中的每个元素和步骤2的结果的组合。
结果是:
files = [fn for fn in os.listdir('C:/Temp/lamip') if fn.endswith('.txt')]
# perhaps filter `files`
def does_fn_contain_string(filename):
with open('C:/Temp/lamip/' + filename) as blargh:
content = blargh.read()
return 'string1' in content and/or 'string2' in content
with open('results.txt', 'w') as output:
for fn in files:
if does_fn_contain_string(fn):
output.write('Current MW in node is {1}\n'.format(fn[:-4]))
else:
output.write('NOT {1}\n'.format(fn[:-4]))发布于 2015-01-16 18:35:20
您可以通过创建一个遍历当前工作目录中所有.txt文件的for循环来实现此目的。
import os
with open("result.txt", "w") as resultfile:
for result in [txt for txt in os.listdir(os.getcwd()) if txt.endswith(".txt")]:
if 'LZY_201_335_R10A01' and 'LZY_201_186_R5U01' in open(result).read():
resultfile.write('Current MW in node is {1}'.format(result[:-4]))
else:
resultfile.write('NOT {0}'.format(result[:-4]))https://stackoverflow.com/questions/27981835
复制相似问题