Есть ли способ закрыть файл, который открывает PdfFileReader?

Я открываю много PDF-файлов и хочу удалить PDF-файлы после их анализа, но файлы остаются открытыми до тех пор, пока программа не завершит работу. Как закрыть PDF-файлы, открытые с помощью 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

person SPYBUG96    schedule 30.10.2017    source источник


Ответы (3)


просто откройте и закройте файл самостоятельно

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

PyPDF2 .read()s поток, который вы передаете, прямо в конструкторе. Таким образом, после первоначального построения объекта вы можете просто выбросить файл.

Менеджер контекста также будет работать:

with open(path, "rb") as f:
    pdf = PyPDF2.PdfFileReader(f)
do_other_stuff_with_pdf(pdf)
person Him    schedule 30.10.2017
comment
Я решил использовать этот ответ в своем собственном коде. Спасибо! - person SPYBUG96; 31.10.2017

При этом:

pdf = PyPDF2.PdfFileReader(file(path, "rb"))

вы передаете ссылку на дескриптор, но не можете контролировать, когда файл будет закрыт.

Вы должны создать контекст с дескриптором вместо того, чтобы передавать его анонимно отсюда:

я бы написал

with open(path,"rb") as f:

    pdf = PyPDF2.PdfFileReader(f)
    #Check for number of pages, prevents out of bounds errors
    ... do your processing
    # Collapse whitespace
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
# now the file is closed by exiting the block, you can delete it
os.remove(path)
# and return the contents
return content
person Jean-François Fabre    schedule 30.10.2017

Да, вы передаете поток PdfFileReader и можете его закрыть. Синтаксис with предпочтительнее сделать это за вас:

def getPDFContent(path):
    with open(path, "rb") as f:
        content = ""
        # Load PDF into pyPDF
        pdf = PyPDF2.PdfFileReader(f)

        #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())
        return content
person de1    schedule 30.10.2017