diff options
author | Barry Warsaw <barry@python.org> | 2014-08-05 11:28:12 -0400 |
---|---|---|
committer | Barry Warsaw <barry@python.org> | 2014-08-05 11:28:12 -0400 |
commit | 7c549c4e6445b25c95491571af8dfa6532570866 (patch) | |
tree | d5f3bf11bea329a38e91ad4bddc66adef5aeae4f /Lib/pathlib.py | |
parent | 17fd1e1013e27032a8a14cc4a1e0521ef75d3699 (diff) | |
download | cpython-git-7c549c4e6445b25c95491571af8dfa6532570866.tar.gz |
- Issue #21539: Add a *exists_ok* argument to `Pathlib.mkdir()` to mimic
`mkdir -p` and `os.makedirs()` functionality. When true, ignore
FileExistsErrors. Patch by Berker Peksag.
(With minor cleanups, additional tests, doc tweaks, etc. by Barry)
Also:
* Remove some unused imports in test_pathlib.py reported by pyflakes.
Diffstat (limited to 'Lib/pathlib.py')
-rw-r--r-- | Lib/pathlib.py | 11 |
1 files changed, 9 insertions, 2 deletions
diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 428de39f96..eff6ae3f0c 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -1106,14 +1106,21 @@ class Path(PurePath): fd = self._raw_open(flags, mode) os.close(fd) - def mkdir(self, mode=0o777, parents=False): + def mkdir(self, mode=0o777, parents=False, exist_ok=False): if self._closed: self._raise_closed() if not parents: - self._accessor.mkdir(self, mode) + try: + self._accessor.mkdir(self, mode) + except FileExistsError: + if not exist_ok or not self.is_dir(): + raise else: try: self._accessor.mkdir(self, mode) + except FileExistsError: + if not exist_ok or not self.is_dir(): + raise except OSError as e: if e.errno != ENOENT: raise |