SPY*_*G96 5 python python-2.7 pypdf2
我打开了很多 PDF,我想在解析后删除这些 PDF,但文件在程序运行完成之前保持打开状态。如何关闭使用 PyPDF2 打开的 PDF?
代码:
def getPDFContent(path):
content = ""
# Load PDF into pyPDF
pdf = PyPDF2.PdfFileReader(file(path, "rb"))
#Check for number of pages, prevents out of bounds errors
max = 0
if pdf.numPages > 3:
max = 3
else:
max = (pdf.numPages - 1)
# Iterate pages
for i in range(0, max):
# Extract text from page and add to content
content += pdf.getPage(i).extractText() + "\n"
# Collapse whitespace
content = " ".join(content.replace(u"\xa0", " ").strip().split())
#pdf.close()
return content
Run Code Online (Sandbox Code Playgroud)
只需自己打开和关闭文件
f = open(path, "rb")
pdf = PyPDF2.PdfFileReader(f)
f.close()
Run Code Online (Sandbox Code Playgroud)
PyPDF2.read()是您传入的流,就在构造函数中。因此,在初始对象构造之后,您可以只扔文件。
上下文管理器也可以工作:
with open(path, "rb") as f:
pdf = PyPDF2.PdfFileReader(f)
do_other_stuff_with_pdf(pdf)
Run Code Online (Sandbox Code Playgroud)