你如何在Python中关闭它?

时间:2015-08-13 19:55:40

标签: python pdf

我需要能够关闭PDF但我还没能弄清楚PyPDF2如何使用Python 2.7

我在下面打开但是然后我尝试了.close():

input1 = PdfFileReader(open(var_loopingpath+f,"rb"))

得到错误:

'PdfFileReader' object has no attribute 'close'

感谢。

1 个答案:

答案 0 :(得分:3)

使用with并且无需关闭文件:

with open(var_loopingpath+f,"rb") as pdf_file:
    input1 = PdfFileReader(pdf_file)
    # rest of code

这样,当Python超出范围时,Python将关闭pdf_file