ValueError: seek of closed file | pdfplumber

问题描述:

I am writing a program that it will extract text from a PDF file using library pdfplumber and I am getting the following error in the last 3 iterations before the end of the for loop.

Do you have any ideas?

Thanks

def changePDF():
    numPages = int(input("how many pages does your pdf have? --> "))
    for i in range(numPages):
        with pdfplumber.open(r'test.pdf') as pdf:
            page = pdf.pages[i]
            print(f"working on page {i}")
    print(page.extract_text())

I am writing a program that it will extract text from a PDF file using library pdfplumber and I am getting the following error in the last 3 iterations before the end of the for loop.

Do you have any ideas?

Thanks

def changePDF():
numPages = int(input("how many pages does your pdf have? --> “))
for i in range(numPages):
with pdfplumber.open(r’test.pdf’) as pdf:
page = pdf.pages[i]
print(f"working on page {i}”)
print(page.extract_text())

答案:

I’m not familiar with pdfplumber but I can make an educated guess that page does not hold all of the data from the file but instead references a location within an open file handle. Once you leave your with block, that file handle is closed and you can no longer access the data.

What you can do is move the with line outside of your for loop and do all of your interaction with the PDF inside that block. That is,

with pdfplumber.open(r'test.pdf') as pdf:
    for i in range(numPages):
        page = pdf.pages[i]
        print(f"working on page {i}")
        print(page.extract_text())

参考链接:
https://stackoverflow.com/questions/62365308/valueerror-seek-of-closed-file-pdfplumber

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值