【问题标题】:fitz.open() not working when in a for loop (FITZ,PYTHON,PYMUPDF)fitz.open() 在 for 循环中不起作用(FITZ、PYTHON、PYMUPDF)
【发布时间】:2021-04-15 16:53:15
【问题描述】:

尝试使用 PyMuPDF 中的 fitz 遍历目录 ('PDFS') 中的文件时,我遇到了困难。 问题是,当我只是在做 document =“somepdf.pdf”时,代码就可以工作,但是一旦我插入一个 for 循环并尝试以这种方式访问​​文件,就会出现这个错误:

文件名、流、文件类型、矩形、宽度、高度、字体大小 RuntimeError: cannot open sample.pdf: No such file or directory

代码如下:

for file in os.listdir('PDFS'):
        if fnmatch.fnmatch(file, '*.pdf'):
            document = file
            doc = fitz.open(document)

感谢您的帮助!

【问题讨论】:

    标签: python pdf pymupdf


    【解决方案1】:

    您要打开的 pdf 文件位于子目录 PDFS 下,例如PDFS/sample.pdf,而您的代码fitz.open(document) 是在当前工作目录下打开文件。所以,修复应该是:

    import fitz
    import os
    import fnmatch
    
    for file in os.listdir('PDFS'):
        if fnmatch.fnmatch(file, '*.pdf'):
            document = os.path.join('PDFS', file)
            doc = fitz.open(document)
    

    此外,使用了相对路径PDFS,因此您必须在PDFS所在的路径下运行代码,例如/your/workspace/:

    /your/workspace > python code.py
    

    否则,

    /your > python workspace/code.py
    
    FileNotFoundError: [WinError 3] The system cannot find the path specified: 'PDFS'
    

    所以,一个好的做法是

    • 如果PDFS 只是用户输入路径,则使用完整路径;否则,

    • 使用脚本路径的相对路径

      script_path = os.path.abspath(__file__)
      project_path = os.path.dirname(script_path)
      pdfs_path = os.path.join(project_path, 'PDFS')
      

    【讨论】:

      【解决方案2】:

      我有同样的问题。这是因为 PyCharm 会自动安装名为 fitz 的模块,而您需要在终端中编写以下内容:

      pip install PyMuPDF
      

      这会自动安装fitz,你可以使用函数fitz.open()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-09-28
        • 2018-09-09
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多