繁体   English   中英

Python - 使用子进程查找目录和子目录中包含特定文本的所有文件

[英]Python - Find all files containing specific text in directories and subdirectories using subprocess

我是 python 的新手。 我正在遍历一组使用变量的商品,我想使用文件中的特定文本单词价格查找文件列表到 grep 所有文件并阅读它。 我有以下代码,但它给[Errno 2] no such files or directory 如果还有其他方法,请有人指导我,在此先感谢

data=os.listdir('./data/pack/')
for goods in data:
    filepath = ('./file/'+ goods + '/cost/')
    grep=subprocess.Popen(['grep','-lir','price', filepath],stdout=subprocess.PIPE)
    found=grep.communicate()[0]
    print(found)

我什至尝试了其他一些方法,如下所示

try:
    grep1=subprocess.Popen('[./file/'+ goods + '/cost/']), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    grep=subprocess.Popen(['grep','-lir','price'],stdin=grep1.stdout,stdout=subprocess.PIPE)
    grep1.stdout.close()
    grep.communicate()
except

但以上两种方法都没有给我结果

谢谢!! 结果找到了!

cmd = 'grep -lir "price"' './file/'+ goods + '/cost/' -i | grep '.txt'
result = subprocess.check_output(cmd, shell=True)

递归遍历文件夹和子文件夹,并获取您要在其中搜索的所有具有所需扩展名的文件。

import os
from glob import glob

dir_path = "path_of_your_directory"
file_extension = "file_extensions_in_which_you_want_to_search"

files = [y for x in os.walk(dir_path) for y in glob(os.path.join(x[0], '*.' + file_extension))]

现在遍历文件,打开每个文件,然后检查要搜索的文本。 您可以使用find()或使用正则表达式进行搜索。

for file_path in files:
    if open(file_path, 'r').read().find('the_text_you_want_to_search') != -1:
        print("found")

暂无
暂无

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

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