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

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


例如文件夹结构


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'


摇曳的蔷薇
浏览 180回答 4
4回答

Helenr

错误是由于缺少完整的文件路径。因此,您需要确保“A/B/C/D.dat”应该存在于您尝试作为 myfile 打开的文件中。您可以将以下代码段添加到您的逻辑中以实现它。for subdir, dirs, files in os.walk(rootdir):    for file in files:        filepath=subdir+'/'+file

慕尼黑5688855

尽管您的解决方案不是最干净的。你得到的错误来自            with open (file, 'rt') as myfile:应该替换为            with open (subdir + "/" + file, 'rt') as myfile:

婷婷同学_

听起来您正在寻找子目录中所有 .dat 文件的第三行。使用 pathlib.Path,您可以通过几个简单的步骤完成很多工作。from pathlib import Pathdoc = []line_number_of_each_file = values = 2for file in Path('C:/A/B').rglob('*.dat'):    doc.append(file.readtext().splitlines()[line_number_of_each_file])print(doc)

侃侃无极

我有一个类似的问题。我的文件结构是这样的:project|__dir1|  |__file_to_read.txt||__dir2   |__file_reader.py为了真正找到另一个文件,我必须走出一个目录,到我.py文件的父目录。我最初使用此代码:import oscurrent_path = os.path.dirname(__file__)file_to_read = os.path.relpath('project/dir1/file_to_read', current_path)这对我有用,但后来我换了一个不同的版本。原因不是您需要担心的任何原因,除了显然下一个模块比os.from pathlib import Pathparent = Path.cwd().parentfile_to_read = Path(f'{parent}/project/dir1/file_to_read.txt').resolve()也许这会更可取,因为它更强烈推荐给我。我希望这对您的问题有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python