【问题标题】:Get list of pdf files in folder获取文件夹中的pdf文件列表
【发布时间】:2015-11-30 12:34:03
【问题描述】:

我想获取文件夹中所有 pdf 文件的文件名列表,我有我的 python 脚本。

现在我有了这个代码:

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:

e = (len(files) - 1)

问题是这段代码找到了文件夹中的所有文件(包括 .py),所以如果我的脚本是文件夹中的最后一个文件(zzzz.py),我会“修复”,然后我减去列表中的最后一个文件我的脚本.py。

我尝试了很多代码,只找到 .pdf,但我离我越近。

【问题讨论】:

  • 将此测试 and f.lower().endswith('.pdf') 添加到您的 files list

标签: python


【解决方案1】:

使用glob 模块:

>>> import glob
>>> glob.glob("*.pdf")
>>> ['308301003.pdf', 'Databricks-how-to-data-import.pdf', 'emr-dg.pdf', 'gfs-sosp2003.pdf']

【讨论】:

    【解决方案2】:

    直接在目录上使用glob 来查找你所有的pdf文件:

    from os import path
    from glob import glob  
    def find_ext(dr, ext):
        return glob(path.join(dr,"*.{}".format(ext)))
    

    演示:

    In [2]: find_ext(".","py")
    Out[2]: 
    ['./server.py',
     './new.py',
     './ffmpeg_split.py',
     './clean_download.py',
     './bad_script.py',
     './test.py',
     './settings.py']
    

    如果你想要忽略大小写的选项:

    from os import path
    from glob import glob
    def find_ext(dr, ext, ig_case=False):
        if ig_case:
            ext =  "".join(["[{}]".format(
                    ch + ch.swapcase())) for ch in ext])
        return glob(path.join(dr, "*." + ext))
    

    演示:

    In [4]: find_ext(".","py",True)
    Out[4]: 
    ['./server.py',
     './new.py',
     './ffmpeg_split.py',
     './clean_download.py',
     './bad_script.py',
     './test.py',
     './settings.py',
     './test.PY']
    

    【讨论】:

    • 我相信您在第二个示例的第 6 行的 ch.swapcase 之后有一个额外的右括号。这真的很棒,谢谢!
    【解决方案3】:

    您只需要过滤文件名,寻找以“.pdf”结尾的文件,对吧?

    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    files = filter(lambda f: f.endswith(('.pdf','.PDF')), files)
    

    现在,您的 files 仅包含以 .pdf 或 .PDF 结尾的文件名称:)

    【讨论】:

    • 我使用你的代码是因为对我来说更容易理解,但我想对大家说声谢谢。非常感谢
    【解决方案4】:

    你可以使用endswith:

    files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.pdf')]
    

    【讨论】:

    • 没有被否决,但在其他答案中可以看到更好的工作工具,例如glob 或 fnmatch。
    【解决方案5】:

    递归获取所有PDF文件:

    import os
    
    all_files = []
    for dirpath, dirnames, filenames in os.walk("."):
        for filename in [f for f in filenames if f.endswith(".pdf")]:
            all_files.append(os.path.join(dirpath, filename)
    

    【讨论】:

      【解决方案6】:

      你也可以使用以下,

      files = filter(
          lambda f: os.path.isfile(f) and f.lower().endswith(".pdf"),
          os.listdir(".")
      )
      file_list = list(files)
      

      或者,在一行中:

      list(filter(lambda f: os.path.isfile(f) and f.lower().endswith(".md"), os.listdir(".")))
      

      您可以使用list() 函数将过滤后的对象转换为列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-27
        • 2011-01-15
        • 1970-01-01
        • 2015-09-08
        • 2017-02-25
        • 2015-04-06
        • 2013-12-25
        • 1970-01-01
        相关资源
        最近更新 更多