如何关闭 pyPDF“PdfFileReader”类文件句柄
这应该是一个非常简单的问题,我无法通过谷歌搜索找到答案:How to close file handle opening by pyPDF "PdfFileReader" Class
Here is snippet:
import os.path
from pyPdf import PdfFileReader
fname = 'my.pdf'
input = PdfFileReader(file(fname, "rb"))
os.rename(fname, 'my_renamed.pdf')
which raises error [32]
谢谢
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
Here is snippet:
import os.path
from pyPdf import PdfFileReader
fname = 'my.pdf'
input = PdfFileReader(file(fname, "rb"))
os.rename(fname, 'my_renamed.pdf')
which raises error [32]
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
操作系统正在阻止文件在其他程序打开时被重命名。这是一件好事(tm)。
Python 的 with 语句会在您执行完操作后自动关闭文件。完成阅读/操作。
如果您仍在使用 Python 2.5,则必须执行特殊导入:
Python 2.6 及更高版本默认启用 with 。
The operating system is preventing a file from being re-named while something else has it open. This is a Good Thing (tm).
Python's with statement will automatically close the file after you're done reading/manipulating it.
If you're still on Python 2.5, you'll have to do a special import:
Python 2.6 and above have with enabled by default.
如果您确实必须从 PdfFileReader 对象访问它(即:如果您自己没有对该文件对象的引用),则可以使用
reader.stream.close()
请注意,PdfFileReader 需要一个打开的文件对象来访问 pdf 的内容(它不会从一开始就将所有内容拉入内存),因此只有在使用完阅读器后才关闭文件。
If you really have to access this from the PdfFileReader object (that is: if you haven't got a reference to the file object yourself), you can use
reader.stream.close()
Note that the PdfFileReader will need an open file object to access the pdf's content (it doesn't pull everything into memory from the start), so only close the file when you are done with the reader.
我建议处理从 PdfFileReader 打开的文件
您的代码将是:
I would sugest to handle the file open out of the PdfFileReader
Your code will be:
而是使用
input=PdfFileReader(file(fname, "rb"))
创建一个像这样的输入流
,当工作完成时使用
inputStream.close()
然后你就可以通过 os 包调用它
instead using
input=PdfFileReader(file(fname, "rb"))
create an input stream like this
and when job is done use
inputStream.close()
then u will be able to call it through os package