如何递归遍历所有子目录和读取文件?

Joe*_*Joe 32 python file

我有一个root-ish目录,其中包含多个子目录,所有子目录都包含文件名data.txt.我想要做的是编写一个接收"root"目录的脚本,然后读取所有子目录并读取子目录中的每个"data.txt",然后将每个data.txt文件中的内容写入输出文件.

这是我的代码片段:

import os
import sys
rootdir = sys.argv[1]

with open('output.txt','w') as fout:
    for root, subFolders, files in os.walk(rootdir):
        for file in files:
            if (file == 'data.txt'):
                #print file
                with open(file,'r') as fin:
                    for lines in fin:
                        dosomething()
Run Code Online (Sandbox Code Playgroud)

我的dosomething()部分 - 如果我只为一个文件运行该部分,我已经测试并确认它可以正常工作.我还确认,如果我告诉它打印文件(注释掉的行),脚本会输出'data.txt'.

现在,如果我运行它,Python会给我这个错误:

File "recursive.py", line 11, in <module>
    with open(file,'r') as fin:
IOError: [Errno 2] No such file or directory: 'data.txt'
Run Code Online (Sandbox Code Playgroud)

我不确定为什么它找不到它 - 毕竟,如果我取消注释'print file'行,它会打印出data.txt.我做错了什么?

Mar*_*ers 54

您需要使用绝对路径,您的file变量只是一个没有目录路径的本地文件名.该root变量是路径:

with open('output.txt','w') as fout:
    for root, subFolders, files in os.walk(rootdir):
        if 'data.txt' in files:
            with open(os.path.join(root, 'data.txt'), 'r') as fin:
                for lines in fin:
                    dosomething()
Run Code Online (Sandbox Code Playgroud)

  • 如果像我一样,任何阅读此内容的人都希望另外过滤正在迭代的文件名,那么这个问题的答案非常有用:http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-递归式的Python (7认同)
  • [`os.walk()`+ follow symlinks](http://stackoverflow.com/questions/3771696/python-os-walk-follow-symlinks)解决了如何使用此链接的方法. (2认同)