Skip to content

Commit 81dcf46

Browse files
committed
PI: Don't load entire file into memory when passed file name
This halves allocated memory when doing a simple PdfWriter(clone_from=«str»)
1 parent 389b579 commit 81dcf46

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

pypdf/_reader.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
Union,
4848
cast,
4949
)
50+
import weakref
5051

5152
from ._encryption import Encryption, PasswordType
5253
from ._page import PageObject, _VirtualList
@@ -310,9 +311,11 @@ def __init__(
310311
"It may not be read correctly.",
311312
__name__,
312313
)
314+
313315
if isinstance(stream, (str, Path)):
314-
with open(stream, "rb") as fh:
315-
stream = BytesIO(fh.read())
316+
stream = open(stream, "rb")
317+
self._finalizer = weakref.finalize(self, stream.close)
318+
316319
self.read(stream)
317320
self.stream = stream
318321

0 commit comments

Comments
 (0)