Python - 循环遍历不同文件夹中的文件

标签 python loops directory nested

我想从嵌套在子文件夹中的多个文件中提取数据。

例如文件夹结构

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/

相关文章:

python - 避免Python中的冗余循环

python - 在python中按顺序重命名文件

python - 将 PyQT/PySide 小部件绑定(bind)到 Python 中的局部变量

python - 不同形状数组的输出索引 Python

python - 如何打开 .data 文件扩展名

Python 套接字点对点

c - 出现不需要的换行符

java - Hangman 赋值和循环条件

java - 如何使用 split() 删除路径中的最后一个目的地?

c# - Dropbox 及其类似 "Folder"的设计