Ask Your Question
1

How can Python pathlib create new directories if they are not already present?

asked 2022-08-21 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-10-17 00:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-21 11:00:00 +0000

Seen: 8 times

Last updated: Oct 17 '22