231

If I wanted to specify a path to save files to and make directories that don’t exist in that path, is it possible to do this using the pathlib library in one line of code?

4 Answers 4

389

Yes, that is Path.mkdir:

pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True) 

From the docs:

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError.

If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

Sign up to request clarification or add additional context in comments.

2 Comments

with exist_ok set to true, does mkdir just overwrite the dir and make it again? Or does it skip (re)making the dir since it already exists?
@PrithviBoinpally the latter—calling mypath.mkdir(exist_ok=True) will not raise an error, and will leave the existing directory associated with mypath intact.
24

If your path includes a filename, e.g.

file_path = "/existing_dir/not_existing_dir/another_dir/a_file_name" 

Then use file_path.parents[0] or file_path.parent:

from pathlib import Path file_path = "/existing_dir/not_existing_dir/another_dir/a_file_name" pathlib.Path(filepath).parent.mkdir(parents=True, exist_ok=True) 

Otherwise, you might encounter PermissionError: [Errno 13] Permission denied later on.

3 Comments

Nice! This is the neatest example and work well.
or even shorter Path(filepath).parent
For the copy cats here pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True)
17

This gives additional control for the case that the path is already there:

path = Path.cwd() / 'new' / 'hi' / 'there' try: path.mkdir(parents=True, exist_ok=False) except FileExistsError: print("Folder is already there") else: print("Folder was created") 

Comments

0

Universal function to create dirs/files that do not exist

def check_and_create_path(self, path: Path): path_way = path.parent if path.is_file() else path path_way.mkdir(parents=True, exist_ok=True) if not path.exists(): path.touch() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.