我正在打开许多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