我已经看到了很多解决方案,但是我没有看到其中的一个解决方案我试图在特定字符串的Python目录中查找每个文件,计算grep返回的行数,并用python记录下来。这是我曾尝试最近:使用Python获取目录中图像名称的grep结果的行数
for f in try_files:
print("trying %s"%f)
s = subprocess.Popen("grep -r '%s' ../dir/*"%f)
print(s)
我收到此错误:
trying accept_button_off_transparent.png
Traceback (most recent call last):
File "findImages.py", line 17, in <module>
s = subprocess.Popen("grep -r %s '../dir/*'"%f)
File "/Users/agsrn/anaconda3/lib/python3.5/subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "/Users/agsrn/anaconda3/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: "grep -r accept_button_off_transparent.png '../dir/*'"
Agsrn-MacBook-Pro:images agsrn$ emacs findImages.py
Agsrn-MacBook-Pro:images agsrn$ python findImages.py
['accept_button_off_transparent.png', 'accept_button_on.png', 'accept_button_on_food.png', 'accept_button_on_transparent.png']
trying accept_button_off_transparent.png
Traceback (most recent call last):
File "findImages.py", line 17, in <module>
s = subprocess.Popen("grep -r '%s' ../dir/*"%f)
File "/Users/agsrn/anaconda3/lib/python3.5/subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "/Users/agsrn/anaconda3/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
最后,我想从Python中执行这个查询:
grep -r "filename" ../dir/* | wc -l
...而将该行数作为一个#我可以用于其他逻辑。什么是最好的方法来做到这一点?
为了清楚起见,我的最终目标是统计目录中的任何/所有文件提及某个字符串列表的次数。我正在寻找文件内的字符串,而不仅仅是文件名。我怀疑grep是一个比Python更快的解决方案,但它在更大的Python例程中,因此是所提出的混合解决方案。
你是开放的具有计数,工程文件的解决方案?或者你只想用grep来做到这一点? – Alejandro