Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.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中递归搜索文件中的字符串_Python_Python 3.x - Fatal编程技术网

如何在python中递归搜索文件中的字符串

如何在python中递归搜索文件中的字符串,python,python-3.x,Python,Python 3.x,我试图在我的C:\中查找所有日志文件,然后在这些日志文件中查找字符串。如果找到该字符串,则输出应该是找到该字符串的日志文件的abs路径。下面是我到现在为止所做的 import os rootdir=('C:\\') for folder,dirs,file in os.walk(rootdir): for files in file: if files.endswith('.log'): fullpath=open(os.path.join(fol

我试图在我的
C:\
中查找所有日志文件,然后在这些日志文件中查找字符串。如果找到该字符串,则输出应该是找到该字符串的日志文件的abs路径。下面是我到现在为止所做的

import os
rootdir=('C:\\')
for folder,dirs,file in os.walk(rootdir):
    for files in file:
        if files.endswith('.log'):
            fullpath=open(os.path.join(folder,files),'r')
            for line in fullpath.read():
                if "saurabh" in line:
                    print(os.path.join(folder,files))

您的代码在以下位置被破坏:

for line in fullpath.read():
语句
fullpath.read()
将以一个字符串的形式返回整个文件,当您对其进行迭代时,您将一次迭代一个字符。您永远不会在单个字符中找到字符串“saurabh”

文件是其自身的行迭代器,因此只需将此语句替换为:

for line in fullpath:
此外,为了保持整洁,您可能希望在完成后关闭文件,可以显式地关闭,也可以使用
with
语句关闭

最后,您可能希望在找到文件时中断,而不是多次打印同一文件(如果字符串多次出现):


那么你的代码怎么了?为什么需要递归解决方案?我没有将输出作为包含“saurabh”的文件的abs路径。出于代码目的,我在其中一个文件中添加了“saurabh”。。。这解决了我的问题。我弄错了。非常感谢
import os
rootdir=('C:\\')
for folder, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.log'):
            fullpath = os.path.join(folder, file)
            with open(fullpath, 'r') as f:
                for line in f:
                    if "saurabh" in line:
                        print(fullpath)
                        break