我有一个包含许多文本文件的文件夹(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')
现在我希望对文件夹中的所有文本文件重复此操作。请帮忙。
模块化!模块化!
好吧,不是要编写不同的Python模块,而是要隔离手头的不同任务。
每个任务都可以独立解决。一、 e.要列出这些文件,您可能需要筛选
os.listdir
。对于步骤2,您是否有1个或1000个文件要搜索并不重要。程序是一样的。您只需遍历在步骤1中找到的每个文件。这表示步骤2可以实现为一个函数,该函数以文件名(以及可能的搜索字符串)作为参数,并返回
True
或False
。步骤3是步骤1中的每个元素与步骤2的结果的组合。
结果是:
您可以通过创建一个
for
循环来完成此操作,该循环将运行当前工作目录中的所有.txt
文件。假设您有一些文件名从
EPA1.txt
到EPA150.txt
,但是您不知道所有的名称,您可以将它们放在一个文件夹中,然后使用os.listdir()
方法读取该文件夹中的所有文件,以获得一个文件名列表。您可以使用listdir("C:/Temp/lamip")
读取文件名。另外,您的
if
语句是错误的,您应该改为:代码如下:
注意:您可以在路径中使用
/
而不是\\
,Python会自动为您转换它们。相关问题 更多 >
编程相关推荐