繁体   English   中英

如何在目录中的所有文本文件中搜索字符串并将找到的结果放在 Python 的文本文件中

[英]How do I search all text files in directory for a string and place the found result in a text file in Python

我正在尝试编写一些 Python 代码来查看目录中的 all.txt 文件以及包含特定字符串的任何文件,将 append 文件名转换为 a.txt 文件。

我目前有以下代码在我 select 单个文件时有效:

 with open('FW_ (Big) Data Engineer.msg datatext.txt') as f:
    if "Data Engineer" in f.read():
        f = open("Data Engineer.txt","a+")
        f.write("Found it, but I would rather have the file name here")
        f.close() 

假设目录路径是“C:\Users\me\textfiles”,我似乎找不到循环遍历该目录中所有文件的方法,查找字符串并将文件名写入例如“ Data Engineer.txt”如果它应该属于那里。

我已经尝试将我的路径定义为变量,但我还没有找到一个可行的解决方案(尝试过 os.scandir 和 Path),我还没有找到一个可行的解决方案来遍历该目录中的所有文件。 我知道 f.write 需要一个字符串,但我认为将变量放在 str() 之间可以解决这个问题。

尝试这个:

import os

# Remember to change these
directory = "test";
text = "Test";
def search(dirname):
    array = [];
    for i in os.listdir(dirname):
        i = os.path.join(dirname, i);
        if(os.path.isdir(i)):
            x = search(i);
            if(not x):
                continue;
            array = array + x;
        else:
            if(text in open(i, "r").read()):
                do_something();
search(directory);

这也将在子目录中搜索。

您可以使用以下代码遍历文件夹:

import os

for filename in os.listdir(directory):
    with open (directory+'/'+filename) as f:
        #your code here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM