递归查找字符串行开头 python

find string line startswith recursively python

我必须递归地找到所有文件(在目录和子目录中)中的所有行(以字符串 "excel" 开头)。我需要为找到的行找到每个文件名(例如: 文件名1: line1成立... 文件名 2:

line2 成立... 在名为 "logfile" 的文件中输出结果 如果没有找到行,文件名不会保存在日志文件中。

import os
word="excel"
from os.path import join
for (dirname, dirs, files) in os.walk('/batch/'):
    for filename in files:
      thefile = os.path.join(dirname,filename)
         for line in files: 
           if line.startswith(word):
                    print (line)
                    print (thefile)

谢谢

这是固定代码。 您不需要重新遍历相同的文件列表。 os.walk() 将 return 目录中的所有子目录,您需要做的就是循环所有目录。

示例代码

import glob
import os
word="excel"

for (dirname, dirs, files) in os.walk("/batch/"):
    for file_ in files :
        if  file_.startswith(word):
                print(file_)
                print(os.path.join(dirname, file_))

    for dir_ in dirs :
        myfiles  = glob.glob(os.path.join(dirname,dir_))
        for myfile in myfiles:
            if  myfile.startswith(word):
                    print(myfile)
                    print(os.path.join(dirname,myfiles))

希望这对您有所帮助

您的代码只有一些小问题:最大的问题是您在文件名而不是文件内容上循环。

import os
word="excel"
from os.path import join
for (dirname, dirs, files) in os.walk('/batch/'):
    for filename in files:
        thefile = os.path.join(dirname, filename)
        with open(thefile) as f:
            for line in f:
                if line.startswith(word):
                    print (line)
                    print (thefile)

编辑:

import os
word="excel"
from os.path import join
with open('log_result.txt', 'w') as log_file:
    for (dirname, dirs, files) in os.walk('/tmp/toto'):
        for filename in files:
            thefile = os.path.join(dirname, filename)
            with open(thefile) as f:
                lines = [line for line in f if line.startswith(word)]
            if lines:
                log_file.write("File {}:\n".format(thefile))
                log_file.writelines(lines)