From f7417bc38a8abbb513cedbc1c59a7b673ca75a54 Mon Sep 17 00:00:00 2001 From: augeos-grosso <94438010+augeos-grosso@users.noreply.github.com> Date: Fri, 14 Jan 2022 05:15:41 +0100 Subject: [PATCH] Address issue #578 (PR #581) Add try-except block in open() (#578), by @augeos-grosso / @johnhuge --- README.md | 1 + pdfplumber/pdf.py | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 78dea577..dbebf4ab 100644 --- a/README.md +++ b/README.md @@ -438,6 +438,7 @@ Many thanks to the following users who've contributed ideas, features, and fixes - [Daniel Peña](https://github.com/trifling) - [bobluda](https://github.com/bobluda) - [@ramcdona](https://github.com/ramcdona) +- [johnhuge](https://github.com/johnhuge) ## Contributing diff --git a/pdfplumber/pdf.py b/pdfplumber/pdf.py index 0c21de81..d8acb6d7 100644 --- a/pdfplumber/pdf.py +++ b/pdfplumber/pdf.py @@ -7,6 +7,7 @@ from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfpage import PDFPage from pdfminer.pdfparser import PDFParser +from pdfminer.psparser import PSException from .container import Container from .page import Page @@ -52,7 +53,11 @@ def __init__( def open(cls, path_or_fp, **kwargs): if isinstance(path_or_fp, (str, pathlib.Path)): fp = open(path_or_fp, "rb") - inst = cls(fp, **kwargs) + try: + inst = cls(fp, **kwargs) + except PSException: + fp.close() + raise inst.close_file = fp.close return inst else: