python - 从目录树中获取任意文件

标签 python file operating-system directory performance

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

最佳答案

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

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

例如:

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

关于python - 从目录树中获取任意文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10304244/

相关文章:

java - 有人可以解释什么是虚拟机以及它们为什么有用吗?

windows - DLL 和注册表有什么问题?

python - PyTorch FasterRCNN 类型错误 : forward() takes 2 positional arguments but 3 were given

python - sys.stdout.encoding、locale.getpreferredencoding() 和 sys.getdefaultencoding() 之间有什么区别?

python - 没有显示任何错误的 Django 表单无效

file - 逐行读取大文件

linux - 我的 Fortran 代码的输出被杀死了,有什么建议吗?

python - 在 Pyswarm PSO 函数中实现约束

java - 测试文件是否为图像文件

php - 如何使用 PHP 检查远程文件是否存在?