在多个文本文件中搜索两个字符串?

2024-09-27 07:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多文本文件的文件夹(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')

现在我希望对文件夹中的所有文本文件重复此操作。请帮忙。


Tags: 文件intxt文件夹aswithresultopen
3条回答

模块化!模块化!

好吧,不是要编写不同的Python模块,而是要隔离手头的不同任务。

  1. 查找要搜索的文件。
  2. 读取文件并找到文本。
  3. 将结果写入单独的文件。

每个任务都可以独立解决。一、 e.要列出这些文件,您可能需要筛选os.listdir

对于步骤2,您是否有1个或1000个文件要搜索并不重要。程序是一样的。您只需遍历在步骤1中找到的每个文件。这表示步骤2可以实现为一个函数,该函数以文件名(以及可能的搜索字符串)作为参数,并返回TrueFalse

步骤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]))

您可以通过创建一个for循环来完成此操作,该循环将运行当前工作目录中的所有.txt文件。

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]))

假设您有一些文件名从EPA1.txtEPA150.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')

注意:您可以在路径中使用/而不是\\,Python会自动为您转换它们。

相关问题 更多 >

    热门问题