我有一个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)