Added support for pathlib Path objects to open and save

This commit is contained in:
Andrew Murray 2015-08-05 20:54:33 +10:00
parent 6ffa876d33
commit 457d39832d

View File

@ -1653,13 +1653,15 @@ class Image(object):
may have been created, and may contain partial data. may have been created, and may contain partial data.
""" """
filename = ""
if isPath(fp): if isPath(fp):
filename = fp filename = fp
else: elif sys.version_info >= (3, 4):
if hasattr(fp, "name") and isPath(fp.name): from pathlib import Path
filename = fp.name if isinstance(fp, Path):
else: filename = str(fp.resolve())
filename = "" elif hasattr(fp, "name") and isPath(fp.name):
filename = fp.name
# may mutate self! # may mutate self!
self.load() self.load()
@ -1687,8 +1689,8 @@ class Image(object):
else: else:
save_handler = SAVE[format.upper()] save_handler = SAVE[format.upper()]
if isPath(fp): if filename:
fp = builtins.open(fp, "wb") fp = builtins.open(filename, "wb")
close = 1 close = 1
else: else:
close = 0 close = 0
@ -2277,11 +2279,15 @@ def open(fp, mode="r"):
if mode != "r": if mode != "r":
raise ValueError("bad mode %r" % mode) raise ValueError("bad mode %r" % mode)
filename = ""
if isPath(fp): if isPath(fp):
filename = fp filename = fp
fp = builtins.open(fp, "rb") elif sys.version_info >= (3, 4):
else: from pathlib import Path
filename = "" if isinstance(fp, Path):
filename = str(fp.resolve())
if filename:
fp = builtins.open(filename, "rb")
try: try:
fp.seek(0) fp.seek(0)