Add an open helper that is compatible with pathlib

This commit is contained in:
James R. Barlow
2017-05-24 16:19:15 -07:00
parent 148b632b4f
commit eb1cd38f6c
2 changed files with 16 additions and 8 deletions
+10 -1
View File
@@ -3,7 +3,7 @@
from functools import partial
from collections.abc import Iterable
from contextlib import suppress
from contextlib import suppress, contextmanager
import sys
import os
@@ -77,3 +77,12 @@ def is_file_writable(test_file):
with suppress(OSError):
os.unlink(test_file)
return True
@contextmanager
def universal_open(p, *args, **kwargs):
"Work around Python 3.5's inability to open(pathlib.Path())"
try:
yield p.open(*args, **kwargs)
except AttributeError:
yield open(p, *args, **kwargs)
+6 -7
View File
@@ -12,6 +12,7 @@ from collections.abc import MutableMapping, Mapping
import warnings
from pathlib import Path
from enum import Enum
from .helpers import universal_open
matrix_mult = pypdf.pdf.utils.matrixMultiply
@@ -593,17 +594,15 @@ def _pdf_get_pageinfo(pdf, pageno: int):
def _pdf_get_all_pageinfo(infile):
if isinstance(infile, Path):
infile = str(infile)
pdf = pypdf.PdfFileReader(infile)
return [PageInfo(pdf, n) for n in range(pdf.numPages)]
with universal_open(infile, 'rb') as f:
pdf = pypdf.PdfFileReader(f)
return [PageInfo(pdf, n) for n in range(pdf.numPages)]
class PageInfo:
def __init__(self, infile, pageno):
self._infile = infile
def __init__(self, pdf, pageno):
self._pageno = pageno
self._pageinfo = _pdf_get_pageinfo(infile, pageno)
self._pageinfo = _pdf_get_pageinfo(pdf, pageno)
@property
def pageno(self):