【问题标题】:Python - loop through files in different foldersPython - 遍历不同文件夹中的文件
【发布时间】:2020-02-14 04:34:06
【问题描述】:

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

例如文件夹结构

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'

【问题讨论】:

    标签: python loops directory nested


    【解决方案1】:

    虽然您的解决方案不是最干净的。你得到的错误来自

                with open (file, 'rt') as myfile:
    

    应该替换为

                with open (subdir + "/" + file, 'rt') as myfile:
    

    【讨论】:

      【解决方案2】:

      错误是由于缺少完整的文件路径。因此,您需要确保“A/B/C/D.dat”应该存在于您尝试作为 myfile 打开的文件中。

      您可以将以下 sn-p 添加到您的逻辑中以实现它。

      for subdir, dirs, files in os.walk(rootdir): for file in files: filepath=subdir+'/'+file

      【讨论】:

        【解决方案3】:

        听起来您正在寻找子目录中所有 .dat 文件的第三行。使用 pathlib.Path,您可以通过几个简单的步骤完成很多此操作。

        from pathlib import Path
        doc = []
        line_number_of_each_file = values = 2
        
        for file in Path('C:/A/B').rglob('*.dat'):
            doc.append(file.readtext().splitlines()[line_number_of_each_file])
        
        print(doc)
        

        【讨论】:

          【解决方案4】:

          我遇到了类似的问题。我的文件结构是这样的:

          project
          |__dir1
          |  |__file_to_read.txt
          |
          |__dir2
             |__file_reader.py
          

          为了真正找到另一个文件,我必须走出一个目录,到我的.py 文件的父目录。我最初使用此代码:

          import os
          
          current_path = os.path.dirname(__file__)
          
          file_to_read = os.path.relpath('project/dir1/file_to_read', current_path)
          

          这对我有用,但后来我换了一个不同的版本。原因不是您需要担心的任何原因,除了显然下一个模块比os 更适合路径爬行。

          from pathlib import Path
          
          parent = Path.cwd().parent
          file_to_read = Path(f'{parent}/project/dir1/file_to_read.txt').resolve()
          

          也许这会更可取,因为它更强烈推荐给我。我希望这对您的问题有所帮助。

          【讨论】:

            【解决方案5】:

            这里的问题是您正在尝试调用 filename.dat。相反,您应该访问 A/B/C/filename.dat 。 为此加入路径名 + 文件名:

            import os
            values = 2
            doc = []
            rootdir = 'A/B/C/'
            
            for subdir, dirs, files in os.walk(rootdir):
                for file in files:
                    if file.endswith('.txt'):
                        print(file)
                        file = os.path.join(rootdir,subdir,file)
                        with open (file, 'rt') as myfile:
                                current_line = 0
                                for mylines in myfile:
                                        if current_line == values:
                                            doc.append(mylines)
                                            break
                                        current_line += 1
                        continue
            
            print(doc)
            

            【讨论】:

              猜你喜欢
              • 2019-09-03
              • 2021-11-22
              • 1970-01-01
              • 1970-01-01
              • 2017-02-08
              • 2017-04-03
              • 1970-01-01
              • 2018-08-13
              • 2020-11-20
              相关资源
              最近更新 更多