[英]Stuck with a ValueError, How to solve it?
我正在做一项任务,我需要使用PyPDF2从PDF中提取文本,并在尝试这样做时收到此错误。 如何解决这个问题? 有人能帮我吗? 先感谢您。
import PyPDF2
textFile = open('foo.txt', 'w')
file = open('foo.pdf','rb')
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
1
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())
--------------------------------------------------------------------------
ValueError Traceback (most recent call
last)
<ipython-input-42-5a892ea3012b> in <module>
----> 1 textFile.write(read_pdf.extractText())
ValueError: I/O operation on closed file.
file.close
textFile.close()
我不确定你是如何结束这个错误的,但这可能会有所帮助:
textFile = open('foo.txt', 'w')
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())
在你使用它之前打开文件似乎对我有用,所以试一试,我们会看到;]
使用with open
你不需要处理异常和关闭文件,它自己处理
import PyPDF2
with open('foo.txt','w') textFile:
with open('foo.pdf','rb') as file:
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.