本文介绍了没有os.walk的Python递归目录读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图通过在 Python 中定义递归函数(而不是使用 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.

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)

我收到以下错误:

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() 返回 None,而不是新的目录名称.您将该结果传递给递归的 walkfn() 函数,然后传递给 os.listdir().

os.chdir() returns None, not the new directory name. You pass that result to the recursive walkfn() function, and then to os.listdir().

无需赋值,只需将path传给walkfn()即可:

There is no need to assign, just pass path to 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)

这篇关于没有os.walk的Python递归目录读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 17:35