【发布时间】: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