Home > Net >  How to close a pdf opened with fitz if I've replaced its variable name?
How to close a pdf opened with fitz if I've replaced its variable name?

Time:12-13

This is a simple issue. I use jupyter notebook for python and usually deal with pdfs using pymupdf.

I usually define pdf = fitz.open('dir/to/file.pdf') but somethimes I forget to close the file before i redefine pdf = fitz.open('dir/to/other_file.pdf')

Sometimes I need to (for example) move or delete file.pdf (the original file) but I can't because python is using it.

Not being an expert, I don't know how to close this file when I have redefined the variable pdf, as obviously pdf.close() would close 'other_file.pdf' and I end up reeinitializing my .ipynb file, which feels dumb.

How can I access an object which variable name has been redefined?

CodePudding user response:

Writting this issue made me think about globals()

Browsing throughout its keys I found that the objects which variables have been reused are stored with dummy names (don't know the term used for them). I found the object I was looking for and I was able to 'close' it.

If there's a better - more elegant solution, I'd be glad to hear about it.

CodePudding user response:

If you do a Document.save("newname.pdf") then that new file, newname.pdf will be immediately available for other processes - it is not blocked by the process you are currently executing.

The original file however, oldname.pdf, from which you have created your Document object remains owned by your current process. It will be freed if you do a Document.close().

But there is a way to work with the oldname.pdf under PyMuPDF without blocking it. It actually entails making a memory-resident copy:

import pathlib
import fitz

pdfbytes = pathlib.Path("oldname.pdf").read_bytes()
# from here on, file oldname.pdf is fully available
doc = fitz.open("pdf", pdfbytes)
# doc can be saved under any name, even the original one.
  • Related