【问题标题】:How to access more than one file in a directory without knowing the name of each file in python如何在不知道python中每个文件的名称的情况下访问目录中的多个文件
【发布时间】:2018-07-19 11:47:16
【问题描述】:

我想访问大约 5000 个文件并一个一个地处理它们。有什么方法可以连续访问每个文件而不用硬编码每个文件的名称?

【问题讨论】:

标签: python jupyter-notebook file-access


【解决方案1】:

以下示例来自此tutorial

import os, sys

# Open a file
path = "/var/www/html/"
dirs = os.listdir( path )

# This would print all the files and directories
for file in dirs:
   print file

【讨论】:

    【解决方案2】:

    如果你的目录包含父目录和文件,你可以使用os.walk() like -

    # Example taken from os.walk documentation
    import os
    from os.path import join, getsize
    for root, dirs, files in os.walk('python/Lib/email'):
        print(root, "consumes", end=" ")
        print(sum(getsize(join(root, name)) for name in files), end=" ")
        print("bytes in", len(files), "non-directory files")
        if 'CVS' in dirs:
            dirs.remove('CVS')
    

    或者你可以使用scandir -

    for entry in os.scandir(path):
        ...
    

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多