【问题标题】:Python: os.listdir alternative/certain extensionsPython:os.listdir 替代/某些扩展
【发布时间】:2011-03-08 13:00:29
【问题描述】:

是否可以使用 os.listdir 命令查看具有特定扩展名的文件?我希望它能够工作,因此它可能只显示最后带有 .f 的文件或文件夹。查了文档,没找到,别问了。

【问题讨论】:

    标签: python operating-system


    【解决方案1】:

    glob 擅长这个:

    import glob
    for f in glob.glob("*.f"):
        print(f)
    

    【讨论】:

    • +1 哇,帮助很大!但是我们不能只做 print(glob.glob("*.py")) 吗?
    • 你可以这样做,glob.glob 返回一个列表,用它做你想做的事。
    【解决方案2】:

    试试这个:

    from os import listdir
    
    extension = '.wantedExtension'
    
    mypath = r'my\path'
    
    filesWithExtension = [ f for f in listdir(mypath) if f[(len(f) - len(extension)):len(f)].find(extension)>=0 ]
    

    【讨论】:

      【解决方案3】:

      别问什么?

      [s for s in os.listdir() if s.endswith('.f')]
      

      如果您想查看扩展列表,可以进行明显的概括,

      [s for s in os.listdir() if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]
      

      或者这种写法更短一些:

      [s for s in os.listdir() if s.rpartition('.')[2] in ('f','c','z')]
      

      【讨论】:

      • 有很多其他语言中的显式函数调用被Python中的内置操作所取代。有时跟踪很棘手。例如,C++ 标准库中的各种适配器模板在 Python 中只是 lambda。这是我最喜欢 Python 的地方之一。
      • “不要问”的意思是“不要问我,‘你检查过文档吗,上面说了什么?’”
      • @Ned:我有点想,这是一个半反问的问题。
      • [s in os.listdir() if s.endswith('.f')] 在此处使用 Python 2.7 会导致语法错误。 [s for s in os.listdir('.') if s.endswith('.f')] 工作
      • 只是想知道,这里的“s”应该是什么?我为自己尝试了代码,它可以工作,但是当使用看似任意的变量名时,我发现很难理解。
      【解决方案4】:
      [s for s in os.listdir() if os.path.splitext(s) == 'f']
      

      【讨论】:

      • 这应该是os.path.splitext(s)[1] == '.f'
      【解决方案5】:

      还有一种可能性目前没有提到:

      import fnmatch
      import os
      
      for file in os.listdir('.'):
          if fnmatch.fnmatch(file, '*.f'):
              print file
      

      其实glob模块就是这样实现的,所以在这种情况下glob更简单更好,但是fnmatch模块在其他情况下可以很方便,例如使用os.walk 进行树遍历时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-20
        • 2021-03-09
        • 2015-09-01
        相关资源
        最近更新 更多