2

我想获取目录树中某处存在的任意文本文件(带有.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
4

2 回答 2

3

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

您可以使用fnmatch此处链接到文档)来简化其余代码。

例如:

...
    if fnmatch.fnmatch(file, '*.txt'):
        print file
...
于 2012-04-24T19:50:03.113 回答
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-04-24T19:53:05.740 回答