在多个文本文件中搜索两个字符串? [英] Searching multiple text files for two strings?

查看:55
本文介绍了在多个文本文件中搜索两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多文本文件的文件夹(EPA10.txt、EPA55.txt、EPA120.txt...、EPA150.txt).我有 2 个要在每个文件中搜索的字符串,搜索结果写入文本文件 result.txt.到目前为止,我已经将它用于单个文件.这是工作代码:

I have a folder with many text files (EPA10.txt, EPA55.txt, EPA120.txt..., EPA150.txt). I have 2 strings that are to be searched in each file and the result of the search is written in a text file result.txt. So far I have it working for a single file. Here is the working code:

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

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

Now I want this to be repeated for all the text files in the folder. Please help.

推荐答案

鉴于您有一些从 EPA1.txtEPA150.txt 命名的文件,但是您不知道所有名称,您可以将它们一起放在一个文件夹中,然后使用 os.listdir() 方法读取该文件夹中的所有文件以获取文件名列表.您可以使用 listdir("C:/Temp/lamip") 读取文件名.

Given that you have some amount of files named from EPA1.txt to EPA150.txt, but you don't know all the names, you can put them altogether inside a folder, then read all the files in that folder using the os.listdir() method to get a list of filenames. You can read the file names using listdir("C:/Temp/lamip").

另外,你的 if 语句是错误的,你应该这样做:

Also, your if statement is wrong, you should do this instead:

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 会自动为您转换它们.

PS: You can use / instead of \\ in your paths, Python automatically converts them for you.

这篇关于在多个文本文件中搜索两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆