Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.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中解析多个文件(相同格式)时使用`for`循环_Python_Loops_Parsing - Fatal编程技术网

在Python中解析多个文件(相同格式)时使用`for`循环

在Python中解析多个文件(相同格式)时使用`for`循环,python,loops,parsing,Python,Loops,Parsing,我正在开发一个Python脚本,希望在其中扫描整个子目录以查找.log文件 要获取.log文件的列表,我可以获取文件名。这是代码 for root, dirs, files in os.walk("Directory to be analyse"): for file in files: if file.endswith('.log'): 现在,如何迭代for循环中的所有文件并获取其内容?在if块中,您可以使用open块在中打开文件并读取每一行 if file.ends

我正在开发一个Python脚本,希望在其中扫描整个子目录以查找
.log
文件

要获取
.log
文件的列表,我可以获取文件名。这是代码

for root, dirs, files in os.walk("Directory to be analyse"):
    for file in files:
        if file.endswith('.log'):

现在,如何迭代for循环中的所有文件并获取其内容?

在if块中,您可以使用open块在
中打开文件并读取每一行

if file.endswith('.log'):
    with open(file,'r') as f:
        for line in f:
            pass  #Do something with each line in the opened file
    print '{} has been closed'.format(file)

希望这有帮助

如果您可以使用
bash
执行此操作,则使用一行程序即可完成此任务

DIR='Directory to be analyse'    
sudo find $DIR -iname \*.log -exec cat {} \;
尝试


您可以使用获取文件的完整路径来打开

这是一个“如何在Python中打开和读取文件”的问题吗?是的。但是想打开多个文件来解析它。没有任何固定数量的文件
import os
for root, dirs, files in os.walk(r'path to open'):
    for file in files:
        if file.endswith('.log'):
            with open(os.path.join(root, file)) as stream:
                for lin in stream:
                    # lin containg the content of each line in the file