我编写了一个Python脚本来查找包含目录中每个文件的特定脚本的行。如果我使这个脚本在具有这些文件的目录中运行,它工作正常。
#!/usr/bin/env python
import os
def searchthis(location, searchterm):
for fname in os.listdir(location):
fullpath = os.path.join(location, fname)
for line in file(fullpath):
if searchterm in line:
print line
searchthis(os.getcwd(), "mystring")
我有什么办法可以用os.walk
执行此操作,并在所有目录和子目录中的每个文件中递归搜索。
答案 0 :(得分:3)
您可以使用这样的简单迭代器:
def all_files(dir):
for root, dirs, files in os.walk(os.path.abspath(dir)):
for f in files:
yield os.path.join(root, f)
例如:
for path in all_files(os.getcwd()):
with open(path) as f:
for n, line in enumerate(f, 1):
if term in line:
print path, n
答案 1 :(得分:2)
#!/usr/bin/env python
import os
def searchthis(location, searchterm):
for dir_path, dirs, file_names in os.walk(location):
for file_name in file_names:
fullpath = os.path.join(dir_path, file_name)
for line in file(fullpath):
if searchterm in line:
print line
searchthis(os.getcwd(), "mystring")