我想从嵌套在子文件夹中的多个文件中提取数据。
例如文件夹结构
A/B/C/D.dat
A/B/E/F.dat
A/B/G/H.dat
我想出的代码是:
import os
values = 2
doc = []
rootdir = 'C:/A/B'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith('.dat'):
with open (file, 'rt') as myfile:
current_line = 0
for mylines in myfile:
if current_line == values:
doc.append()
break
current_line += 1
continue
print(doc)
我努力解决的错误:
...with open (file, 'rt') as myfile:
IOError: [Errno 2] No such file or directory: 'D.dat'
最佳答案
尽管您的解决方案不是最干净的。您遇到的错误来自
with open (file, 'rt') as myfile:
应替换为
with open (subdir + "/" + file, 'rt') as myfile:
关于Python - 循环遍历不同文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60220043/