【问题标题】:Python - Find all files containing specific text in directories and subdirectories using subprocessPython - 使用子进程在目录和子目录中查找包含特定文本的所有文件
【发布时间】:2020-09-04 05:44:11
【问题描述】:

我是 python 新手。 我正在遍历一组使用 variable goods 我想在文件中使用特定文本词 price 查找文件列表以 grep 所有文件并阅读它。 我有以下代码,但它没有给出 [Errno 2] 没有这样的文件或目录。如果还有其他方法,请有人指导我,提前谢谢

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)

【问题讨论】:

  • 您想在其中查找名称为 price 的文件吗?你能进一步解释一下吗?
  • @AmogChandrashekar 查找文件中包含文本单词“price”的所有文件。

标签: python linux shell grep subprocess


【解决方案1】:

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

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()regular expressions 进行搜索。

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

【讨论】:

  • 不工作我收到错误,因为无法打开文件'example.py':[Errno 2] 没有这样的文件或目录
  • 查看我是否在特定目录中 grep -lir price 会获取所有文件。现在我正在编写一个脚本,但我不知道如何在子进程中使用。
  • 你为什么使用 listdir 两次?你也想递归查找子目录中的文件吗?
  • 我已经相应地编辑了答案,现在检查这是否适合你。
  • 感谢您的回答,但我在 grep cmd 中找到了
猜你喜欢
  • 2023-01-04
  • 1970-01-01
  • 2020-08-10
  • 2011-02-21
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多