如何关闭pyPDF"PdfFileReader"类文件句柄 [英] How to close pyPDF "PdfFileReader" Class file handle
问题描述
这应该是一个非常简单的问题,我无法通过Google搜索找到答案:如何关闭由pyPDF"PdfFileReader"类打开的文件句柄
this should be very simple question, for which I couldn't find answer by Google search: How to close file handle opened by pyPDF "PdfFileReader" Class
以下是代码段:
import os.path
from pyPdf import PdfFileReader
fname = 'my.pdf'
input = PdfFileReader(file(fname, "rb"))
os.rename(fname, 'my_renamed.pdf')
这会引发错误[32]
which raises error [32]
谢谢
推荐答案
在其他文件打开的情况下,操作系统阻止文件重命名.这是一件好事(tm).
The operating system is preventing a file from being re-named while something else has it open. This is a Good Thing (tm).
Python的 with 语句将在您关闭后自动关闭文件阅读/操作完毕.
Python's with statement will automatically close the file after you're done reading/manipulating it.
with open(fname, "rb") as f:
input = PdfFileReader(f, "rb"))
os.rename(fname, 'my_renamed.pdf')
如果您仍在使用Python 2.5,则必须进行特殊导入:
If you're still on Python 2.5, you'll have to do a special import:
from __future__ import with_statement
Python 2.6及更高版本已默认启用.
Python 2.6 and above have with enabled by default.
这篇关于如何关闭pyPDF"PdfFileReader"类文件句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!