ValueError: seek of closed file Working on PyPDF2 and getting this error
ValueError: seek of closed file Working on PyPDF2 and getting this error
我正在尝试从 pdf 文件中获取文本。下面是代码:
from PyPDF2 import PdfFileReader
with open('HTTP_Book.pdf', 'rb') as file:
pdf = PdfFileReader(file)
page = pdf.getPage(1)
#print(dir(page))
print(page.extractText())
这给了我错误
ValueError: seek of closed file
我只是把代码放在with
语句下,它工作正常。我的问题是:为什么会这样?我已经将信息存储在 'pdf' 对象中,因此我应该能够在块外访问它。
PdfFileReader
expects a seekable, open, steam. It does not load the entire file into memory, so you have to keep it open to run the methods, like getPage
。您关于创建 reader 自动读取整个文件的假设是不正确的。
一个with
statement operates on a context manager,比如一个文件。当 with
结束时,调用上下文管理器的 __exit__
方法。在这种情况下,它会关闭您的 PdfFildReader
试图用来获取第二页的文件句柄。
如您所见,正确的步骤是在关闭文件之前从 PDF 中阅读您必须阅读的内容。如果且仅当您的程序需要打开 PDF 直到最后,您可以将文件名直接传递给 PdfFileReader
。在那之后没有(记录的)关闭文件的方法,所以我会推荐你原来的方法:
from PyPDF2 import PdfFileReader
with open('HTTP_Book.pdf', 'rb') as file:
pdf = PdfFileReader(file)
page = pdf.getPage(1)
print(page.extractText())
# file is closed here, pdf will no longer do its job
我正在尝试从 pdf 文件中获取文本。下面是代码:
from PyPDF2 import PdfFileReader
with open('HTTP_Book.pdf', 'rb') as file:
pdf = PdfFileReader(file)
page = pdf.getPage(1)
#print(dir(page))
print(page.extractText())
这给了我错误
ValueError: seek of closed file
我只是把代码放在with
语句下,它工作正常。我的问题是:为什么会这样?我已经将信息存储在 'pdf' 对象中,因此我应该能够在块外访问它。
PdfFileReader
expects a seekable, open, steam. It does not load the entire file into memory, so you have to keep it open to run the methods, like getPage
。您关于创建 reader 自动读取整个文件的假设是不正确的。
一个with
statement operates on a context manager,比如一个文件。当 with
结束时,调用上下文管理器的 __exit__
方法。在这种情况下,它会关闭您的 PdfFildReader
试图用来获取第二页的文件句柄。
如您所见,正确的步骤是在关闭文件之前从 PDF 中阅读您必须阅读的内容。如果且仅当您的程序需要打开 PDF 直到最后,您可以将文件名直接传递给 PdfFileReader
。在那之后没有(记录的)关闭文件的方法,所以我会推荐你原来的方法:
from PyPDF2 import PdfFileReader
with open('HTTP_Book.pdf', 'rb') as file:
pdf = PdfFileReader(file)
page = pdf.getPage(1)
print(page.extractText())
# file is closed here, pdf will no longer do its job