问题描述:
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