【问题标题】:Get an arbitrary file from a directory tree从目录树中获取任意文件
【发布时间】:2012-05-05 11:07:32
【问题描述】:

我想获取目录树中某处存在的任意文本文件(带有 .txt 后缀)的路径。该文件不应隐藏或在隐藏目录中。

我尝试编写代码,但看起来有点麻烦。您将如何改进它以避免无用的步骤?

def getSomeTextFile(rootDir):
  """Get the path to arbitrary text file under the rootDir"""
  for root, dirs, files in os.walk(rootDir):
    for f in files:
      path = os.path.join(root, f)                                        
      ext = path.split(".")[-1]
      if ext.lower() == "txt":
        # it shouldn't be hidden or in hidden directory
        if not "/." in path:
          return path               
  return "" # there isn't any text file

【问题讨论】:

  • 我可能会使用splitext 而不是手动拆分,但除此之外,我觉得它看起来不错。

标签: python file operating-system directory performance


【解决方案1】:

使用os.walk(如您的示例)绝对是一个好的开始。

您可以使用fnmatch (link to the docs here) 来简化其余代码。

例如:

...
    if fnmatch.fnmatch(file, '*.txt'):
        print file
...

【讨论】:

    【解决方案2】:

    我会使用fnmatch 而不是字符串操作。

    import os, os.path, fnmatch
    
    def find_files(root, pattern, exclude_hidden=True):
        """ Get the path to arbitrary .ext file under the root dir """
        for dir, _, files in os.walk(root):
            for f in fnmatch.filter(files, pattern):
                path = os.path.join(dir, f)
                if '/.' not in path or not exclude_hidden:
                    yield path
    

    我还将函数重写为更通用(和“pythonic”)。要仅获取一个路径名,请像这样调用它:

     first_txt = next(find_files(some_dir, '*.txt'))
    

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2017-10-28
      • 2021-09-25
      • 2016-07-15
      • 1970-01-01
      • 2017-07-11
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多