简体   繁体   English

如何关闭pyPDF“PdfFileReader”类文件句柄

[英]How to close pyPDF “PdfFileReader” Class file handle

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这应该是一个非常简单的问题,我无法通过 Google 搜索找到答案:How to close file handle opens 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]这引发了错误 [32]

Thanks谢谢

The operating system is preventing a file from being re-named while something else has it open.操作系统阻止文件在其他文件打开时被重命名。 This is a Good Thing (tm).这是一件好事(tm)。

Python's with statement will automatically close the file after you're done reading/manipulating it. Python 的with语句将在您完成阅读/操作后自动关闭文件。

with open(fname, "rb") as f:
  input = PdfFileReader(f, "rb"))

os.rename(fname, 'my_renamed.pdf')

If you're still on Python 2.5, you'll have to do a special import:如果您仍在使用 Python 2.5,则必须进行特殊导入:

from __future__ import with_statement

Python 2.6 and above have with enabled by default. Python 2.6 及更高版本默认启用。

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()如果您真的必须从 PdfFileReader 对象访问它(即:如果您自己没有对文件对象的引用),则可以使用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 将需要一个打开的文件对象来访问 pdf 的内容(它不会从一开始就将所有内容都拉入内存),因此只有在您完成阅读器后才关闭文件。

I would sugest to handle the file open out of the PdfFileReader我会建议处理从 PdfFileReader 打开的文件

Your code will be:您的代码将是:

import os.path
from pyPdf import PdfFileReader

fname = 'my.pdf'
fh = file(fname, "rb")
input = PdfFileReader(fh)

fh.close()
os.rename(fname, 'my_renamed.pdf')

instead using input=PdfFileReader(file(fname, "rb")) create an input stream like this而是使用input=PdfFileReader(file(fname, "rb"))创建这样的输入流

inputStream=file(fname, "rb")
    input=PdfFileReader(inputStream)

and when job is done use inputStream.close() then u will be able to call it through os package当工作完成后使用inputStream.close()然后你就可以通过 os 包调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM