【问题标题】:How to list only regular files (excluding directories) under a directory in Python如何在Python中仅列出目录下的常规文件(不包括目录)
【发布时间】:2012-03-18 18:01:39
【问题描述】:

可以使用os.listdir('somedir')获取somedir下的所有文件。但是,如果我想要的只是常规文件(不包括目录),比如 shell 下 find . -type f 的结果。

我知道可以使用[path for path in os.listdir('somedir') if not os.path.isdir('somedir/'+path)] 来获得与此相关问题类似的结果:How to list only top level directories in Python?。只是想知道是否有更简洁的方法。

【问题讨论】:

    标签: python filesystems


    【解决方案1】:

    你可以使用os.walk,它返回一个包含路径、文件夹和文件的元组:

    files = next(os.walk('somedir'))[2]
    

    【讨论】:

      【解决方案2】:

      我有几种方法可以完成这些任务。我无法评论解决方案的简洁性。 FWIW 他们在这里:

      1. 下面的代码将获取所有以 .txt 结尾的文件。您可能想要删除“.endswith”部分

      import os
      for root, dirs, files in os.walk('./'): #current directory in terminal
           for file in files:
                   if file.endswith('.txt'):
                   #here you can do whatever you want to with the file.
      

      2.这里的代码将假定路径已提供给函数,并将所有 .txt 文件附加到列表中,如果路径中有子目录,它将子目录中的这些文件附加到子文件中

      def readFilesNameList(self, path):
          basePath = path
          allfiles = []
          subfiles = []
          for root, dirs, files in os.walk(basePath):
            for f in files:
               if f.endswith('.txt'):
                   allfiles.append(os.path.join(root,f))
                   if root!=basePath:
                       subfiles.append(os.path.join(root, f))
      

      我知道代码本质上只是骨架,但我认为您可以了解总体情况。
      如果您找到简洁的方法,请发布! :)

      【讨论】:

        【解决方案3】:

        如果您只想要顶级目录中的文件,较早的os.walk 答案是完美的。但是,如果您也想要子目录的文件(例如find),则需要处理每个目录,例如:

        def find_files(path):
            for prefix, _, files in os.walk(path):
                for name in files:
                    yield os.path.join(prefix, name)
        

        现在list(find_files('.'))find . -type f -print 会提供给您的相同内容的列表(list 是因为 find_files 是一个生成器,以防不明显)。

        【讨论】:

          猜你喜欢
          • 2010-12-10
          • 2011-02-21
          • 1970-01-01
          • 2021-03-30
          • 2017-01-07
          • 2013-08-04
          • 2012-07-08
          • 2018-05-02
          相关资源
          最近更新 更多