python - fitz.open() 在 for 循环中不起作用(FITZ、PYTHON、PYMUPDF)

标签 python pdf pymupdf

当我尝试使用 PyMuPDF 中的 fitz 迭代目录(“PDFS”)中的文件时,我遇到了困难。 问题是,当我只是执行 document = "somepdf.pdf"时,代码可以工作,但是一旦我插入 for 循环并尝试访问文件,就会出现此错误:

文件名、流、文件类型、矩形、宽度、高度、字体大小 运行时错误:无法打开sample.pdf:没有这样的文件或目录

这是代码:

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

感谢您的帮助!

最佳答案

您要打开的 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')
    

关于python - fitz.open() 在 for 循环中不起作用(FITZ、PYTHON、PYMUPDF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67112724/

相关文章:

python - Django 中间件 process_template_response 方法未被调用

python - PyQt4无法导入Qsci

python - xlrd 和 xlwt python 库的日期时间问题

php - 使用MySQL数据库中的数据填写PDF表单

python - 无法阅读在线提供的 pdf 文件的特定页面的内容

python - conv2d_transpose 在进行预测时依赖于 batch_size

ios - UIWebView 中的 pdf 文件 : change the language of the page number infobox

linux - PDF 转文本(多页)

python - PyMuPDF Pixmap tobytes() 返回属性错误