How can I safely create a nested directory | PythonThe pathlib library and its .mkdir() method offer a technique to safely create a nested directory. If you are using Python 3.5 or above, use pathlib.Path.mkdir:
from pathlib import Path Path("/myDir/nested").mkdir(parents=True, exist_ok=True) print("done")pathlib.Path.mkdir as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don't need or want the parents to be created, skip the parents argument.
exist_ok=TrueIn order to create the directory without causing exceptions and errors add the exist_ok flag to mkdir() so that it does not raise a FileExistsError if the directory already exists. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. If using Python 3.4 , even though it comes with pathlib, it is missing the useful exist_ok option.
parents=TrueIf 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.
TypeError: mkdir() got an unexpected keyword argument 'exists_ok'
from pathlib import Path p = Path("/MyDir/directory") p.mkdir(exists_ok=True, parents=True)In some cases, if you are using older versions of Python, you will get the following exception.
If you are using the latest versions of Python , change the line like the following:
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python
- Difference Between Static and Class Methods in Python?