有没有办法关闭 PdfFileReader 打开的文件? [英] Is there a way to close the file PdfFileReader opens?

查看:54
本文介绍了有没有办法关闭 PdfFileReader 打开的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开了很多 PDF,我想在解析后删除这些 PDF,但文件在程序运行完成之前保持打开状态.如何关闭使用 PyPDF2 打开的 PDF?

I'm opening a lot of PDF's and I want to delete the PDF's after they have been parsed, but the files remain open until the program is done running. How do I close the PDf's I open using PyPDF2?

代码:

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

推荐答案

只需自己打开和关闭文件

just open and close the file yourself

f = open(path, "rb")
pdf = PyPDF2.PdfFileReader(f)
f.close()

PyPDF2 .read() 是您传入的流,就在构造函数中.所以在初始对象构建之后,你可以直接扔文件.

PyPDF2 .read()s the stream that you pass in, right in the constructor. So after the initial object construction, you can just toss the file.

上下文管理器也可以:

with open(path, "rb") as f:
    pdf = PyPDF2.PdfFileReader(f)
do_other_stuff_with_pdf(pdf)

这篇关于有没有办法关闭 PdfFileReader 打开的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆