From 457d39832d4f433a59c78598849eef3d073cf7e5 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 5 Aug 2015 20:54:33 +1000 Subject: [PATCH] Added support for pathlib Path objects to open and save --- PIL/Image.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/PIL/Image.py b/PIL/Image.py index 861599bf7..87d77ef09 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1653,13 +1653,15 @@ class Image(object): may have been created, and may contain partial data. """ + filename = "" if isPath(fp): filename = fp - else: - if hasattr(fp, "name") and isPath(fp.name): - filename = fp.name - else: - filename = "" + elif sys.version_info >= (3, 4): + from pathlib import Path + if isinstance(fp, Path): + filename = str(fp.resolve()) + elif hasattr(fp, "name") and isPath(fp.name): + filename = fp.name # may mutate self! self.load() @@ -1687,8 +1689,8 @@ class Image(object): else: save_handler = SAVE[format.upper()] - if isPath(fp): - fp = builtins.open(fp, "wb") + if filename: + fp = builtins.open(filename, "wb") close = 1 else: close = 0 @@ -2277,11 +2279,15 @@ def open(fp, mode="r"): if mode != "r": raise ValueError("bad mode %r" % mode) + filename = "" if isPath(fp): filename = fp - fp = builtins.open(fp, "rb") - else: - filename = "" + elif sys.version_info >= (3, 4): + from pathlib import Path + if isinstance(fp, Path): + filename = str(fp.resolve()) + if filename: + fp = builtins.open(filename, "rb") try: fp.seek(0)