我的文件夹中包含许多文本文件(EPA10.txt,EPA55.txt,EPA120.txt ...,EPA150.txt)。我在每个文件中都有2个要搜索的字符串,搜索结果写在文本文件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')
现在,我希望对文件夹中的所有文本文件重复此操作。请帮忙。
假设您有一些名为从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会自动为您转换它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句