【问题标题】:How to open all files in a folder in Python? [duplicate]如何在 Python 中打开文件夹中的所有文件? [复制]
【发布时间】:2021-06-05 09:28:07
【问题描述】:

如何在python中打开一个文件夹中的所有文件?我需要打开一个文件夹中的所有文件,以便为这些文件编制索引以进行语言处理。

【问题讨论】:

标签: python file directory


【解决方案1】:

这里有一个例子。这是它的作用:

  1. os.listdir('yourBasebasePath') 返回目录中的文件列表
  2. with open(os.path.join(os.getcwd(), filename), 'r') 以只读方式打开当前文件(您将无法在里面写入)
import os
for filename in os.listdir('yourBasebasePath'):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: 
      # do your stuff

How to open every file in a folder

【讨论】:

    【解决方案2】:

    我建议查看pathlibhttps://docs.python.org/3/library/pathlib.html

    你可以这样做:

    from pathlib import Path
    
    folder = Path('<folder to index>')
    
    # get all the files in the folder
    files = folder.glob('**/*.csv') # assuming the files are csv
    
    for file in files:
       with open(file, 'r') as f:
           print(f.readlines())
    
    

    【讨论】:

      【解决方案3】:

      您可以使用 os.walk 列出文件夹中的所有文件。 你可以参考os.walk文档

      import os
      folderpath = r'folderpath'
      for root, dirs, files in os.walk(folderpath, topdown=False):
          for name in files:
              print(os.path.join(root, name))
          for name in dirs:
              print(os.path.join(root, name))
      

      【讨论】:

        【解决方案4】:

        你可以使用

        import os
        os.walk()
        

        【讨论】:

          猜你喜欢
          • 2017-10-27
          • 2016-12-24
          • 1970-01-01
          • 2018-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-13
          相关资源
          最近更新 更多