Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用递归python查找字符串行starts_Python_Startswith - Fatal编程技术网

使用递归python查找字符串行starts

使用递归python查找字符串行starts,python,startswith,Python,Startswith,我必须递归地查找所有文件(在目录和子目录中)中的所有行(以字符串“excel”开头)。我需要找到的每个文件名行(例如: 文件名1: 一号线成立。。。 文件名2: 第二行成立。。。 在名为“logfile”的文件中输出结果 如果未找到行,则文件名未保存在日志文件中 import os word="excel" from os.path import join for (dirname, dirs, files) in os.walk('/batch/'): for filename in

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

第二行成立。。。 在名为“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)
谢谢

这是固定代码。 您不需要重新遍历相同的文件列表。 walk()将返回目录中的所有子目录,只需循环所有目录即可

示例代码

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)
编辑:


还有?这段代码是什么?它能工作吗?如果不能,为什么不能?递归地:你不需要一个函数来调用它自己吗?我想
os.walk
的操作意味着:它遍历一个目录树。这段代码工作得很好。最后一件事,作为结果,我如何将找到的行放在同一个文件名下?例如:filename all lines foundFileName 2结果…将这些重定向到名为“Logresult.txt”的文件。非常感谢您的帮助Hi Django,感谢您的快速回复。结果是正确的,但我只需要包含单词“excel”的文件名(和行)(并非所有文件名)…我调整了编辑
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)