Path.mkdir() can create zero or more directories as shown below:
*Memos:
- There is the 1st argument for Path() (Required-Type:
str
,bytes
or os.PathLike). *Its argument name doesn't exist. - The 1st argument is
mode
formkdir()
(Optional-Default:0o777
-Type:int
). - The 2nd argument is
parents
formkdir()
(Optional-Default:False
-Type:bool
): *Memos:- If it's
False
, the path with a target directory and one or more non-existent parent directories cannot be created, getting FileNotFoundError. - If it's
True
, the path with a target directory and one or more non-existent parent directories can be created, not gettingFileNotFoundError
. - Basically,
True
is set to it.
- If it's
- The 3rd argument is
exist_ok
formkdir()
(Optional-Default:False
-Type:bool
): *Memos:- If it's
False
, FileExistsError is raised for an existent path. - If it's
True
,FileExistsError
isn't raised for an existent path. - Basically,
True
is set to it.
- If it's
# Parent directories
# ↓↓↓↓ ↓↓↓↓↓↓
p = Path('dir3/dir3_1/dir3_1_1')
# ↑↑↑↑↑↑↑↑
# A target directory
1. Creating dir1
is successful:
from pathlib import Path
p = Path('dir1')
p.mkdir()
# Or
# p.mkdir(mode=0o777, parents=False, exist_ok=False)
# my_project
# └-dir1 <- Here
2. Recreateing dir1
is failed and gets FileExistsError
:
from pathlib import Path
p = Path('dir1')
p.mkdir()
# FileExistsError: [Errno 17] File exists: 'dir1'
# my_project
# └-dir1
3. Recreating dir1
with exist_ok=True
is failed but doesn't get FileExistsError
:
from pathlib import Path
p = Path('dir1')
p.mkdir(exist_ok=True)
# my_project
# └-dir1
4. Creating dir1_1
in dir1
is successful:
from pathlib import Path
p = Path('dir1/dir1_1')
p.mkdir()
# my_project
# └-dir1
# └-dir1_1 <- Here
5. Creating dir2/dir2_1
is failed and gets FileNotFoundError
:
from pathlib import Path
p = Path('dir2/dir2_1')
p.mkdir()
# FileNotFoundError: [Errno 2] No such file or directory: 'dir2/dir2_1'
# my_project
# └-dir1
# └-dir1_1
6. Creating dir2/dir2_1
with parents=True
is successful:
from pathlib import Path
p = Path('dir2/dir2_1')
p.mkdir(parents=True)
# my_project
# |-dir1
# | └-dir1_1
# └-dir2 <- Here
# └-dir2_1 <- Here
7. Creating dir3/dir3_1/dir3_1_1
with parents=True
and exist_ok=True
is successful:
from pathlib import Path
p = Path('dir3/dir3_1/dir3_1_1')
p.mkdir(parents=True, exist_ok=True)
# my_project
# |-dir1
# | └-dir1_1
# |-dir2
# | └-dir2_1
# └-dir3 <- Here
# └-dir3_1 <- Here
# └-dir3_1_1 <- Here
8. Recreating dir3/dir3_1/dir3_1_1
with parents=True
and exist_ok=True
is failed but doesn't get FileExistsError:
from pathlib import Path
p = Path('dir3/dir3_1/dir3_1_1')
p.mkdir(parents=True, exist_ok=True)
# my_project
# |-dir1
# | └-dir1_1
# |-dir2
# | └-dir2_1
# └-dir3
# └-dir3_1
# └-dir3_1_1
Top comments (0)