微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决fitz.open() 在 for 循环中不起作用FITZ、PYTHON、PYMUPDF

在尝试使用 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)

感谢您的帮助!

解决方法

您要打开的 pdf 文件位于子目录 def __init__(self,scope: cdk.Construct,construct_id: str,cidr_range: str,**kwargs) -> None: super().__init__(scope,construct_id,**kwargs) self.vpc = ec2.Vpc(self,"VPC",nat_gateway_subnets=???,nat_gateways=3,max_azs=3,cidr=cidr_range,subnet_configuration=[ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PUBLIC,name="Public-Firewall",cidr_mask=25 ),ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PUBLIC,name="Public",ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PRIVATE,name="Private-Primary",cidr_mask=24 ),name="Private-Secondary",ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.ISOLATED,name="Private-PrivateLink/AWS",name="Private-TGW",cidr_mask=25 ) ],) 下,例如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
,

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

pip install PyMuPDF

这将自动安装 fitz 并且您可以使用函数fitz.open()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。