[英]Is there a way to close the file PdfFileReader opens?
我打开了很多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
只需自己打开和关闭文件
f = open(path, "rb")
pdf = PyPDF2.PdfFileReader(f)
f.close()
PyPDF2 .read()
是你在构造函数中传入的流。 所以在初始对象构造之后,你可以抛出文件。
上下文管理器也可以工作:
with open(path, "rb") as f:
pdf = PyPDF2.PdfFileReader(f)
do_other_stuff_with_pdf(pdf)
这样做时:
pdf = PyPDF2.PdfFileReader(file(path, "rb"))
您正在尝试对句柄的引用,但您无法控制文件何时关闭。
您应该使用句柄创建上下文,而不是从此处匿名传递它:
我会写的
with open(path,"rb") as f:
pdf = PyPDF2.PdfFileReader(f)
#Check for number of pages, prevents out of bounds errors
... do your processing
# Collapse whitespace
content = " ".join(content.replace(u"\xa0", " ").strip().split())
# now the file is closed by exiting the block, you can delete it
os.remove(path)
# and return the contents
return content
是的,您正在将流传递给PdfFileReader,您可以将其关闭。 with
语法最适合您:
def getPDFContent(path):
with open(path, "rb") as f:
content = ""
# Load PDF into pyPDF
pdf = PyPDF2.PdfFileReader(f)
#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())
return content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.