Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Python pathlib can create new directories if they are not already present by using the mkdir() method. This method creates a new directory and returns a Path object for the newly created directory.

Here is an example:

from pathlib import Path

# create a Path object for the new directory
new_directory = Path('path/to/new/directory')

# create the directory if it does not already exist
if not new_directory.exists():
    new_directory.mkdir()

# check if the directory exists
if new_directory.exists():
    print("Directory created successfully!")

In the example above, the Path object is created for the new directory. The exists() method is used to check if the directory already exists. If it does not exist, the mkdir() method is called to create the new directory. Finally, we check if the directory exists by calling the exists() method again.