简体   繁体   English

没有os.walk的Python递归目录读取

[英]Python recursive directory reading without os.walk

I am trying to walk through tree of directories and search for data in output text files by defining a recursive function (and not using os.walk) in Python. 我试图遍历目录树并通过在Python中定义一个递归函数(而不使用os.walk)来搜索输出文本文件中的数据。

import os

def walkfn(dirname):
    if os.path.exists('output'):
        file1 = open('output')
        for line in file1:
            if line.startswith('Final value:'):
                print line
    else:
        for name in os.listdir(dirname):
            path = os.path.join(dirname, name)
            if os.path.isdir(path):
                print "'", name, "'"
                newdir = os.chdir(path)
                walkfn(newdir)

cwd = os.getcwd()
walkfn(cwd)

I am getting the following error: 我收到以下错误:

Traceback (most recent call last):
  File "/home/Python Work/Test2.py", line 24, in <module>
    walkfn(cwd)
  File "/home/Python Work/Test2.py", line 19, in walkfn
    walkfn(newdir)
  File "/home/Python Work/Test2.py", line 12, in walkfn
    for name in os.listdir(dirname):
TypeError: coercing to Unicode: need string or buffer, NoneType found

os.chdir() returns None , not the new directory name. os.chdir()返回None ,而不是新的目录名称。 You pass that result to the recursive walkfn() function, and then to os.listdir() . 您将该结果传递给递归walkfn()函数,然后传递给os.listdir()

There is no need to assign, just pass path to walkfn() : 无需分配,只需将path传递给walkfn()

for name in os.listdir(dirname):
    path = os.path.join(dirname, name)
    if os.path.isdir(path):
        print "'", name, "'"
        os.chdir(path)
        walkfn(path)

You usually want to avoid changing directories; 您通常要避免更改目录; there is no need to if your code uses absolute paths: 如果您的代码使用绝对路径,则不需要:

def walkfn(dirname):
    output = os.path.join(dirname, 'output')
    if os.path.exists(output):
        with open(output) as file1:
            for line in file1:
                if line.startswith('Final value:'):
                    print line
    else:
        for name in os.listdir(dirname):
            path = os.path.join(dirname, name)
            if os.path.isdir(path):
                print "'", name, "'"
                walkfn(path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM