2

我编写了一个 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并在所有目录和子目录中存在的每个文件中递归搜索。

4

2 回答 2

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
于 2012-08-23T08:34:12.323 回答
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")
于 2012-08-23T08:33:49.220 回答