从一个目录获取任意文件

2024-04-25 19:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个任意文本文件的路径(后缀为.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

Tags: 文件thepathtextin目录txtfor
2条回答

使用os.walk(就像在您的例子中一样)绝对是一个好的开始。在

您可以使用fnmatchlink to the docs here)来简化其余的代码。在

例如:

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

我将使用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”)。要只获得一个路径名,请这样称呼它:

^{pr2}$

相关问题 更多 >