ValueError: seek of closed file | pdfplumber

发布时间:2023年12月18日

问题描述:

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

文章来源:https://blog.csdn.net/qq_39698985/article/details/135054540
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。