Thursday, January 9, 2025
HomeProgrammingCreate a directory in Python

Create a directory in Python

In Python, you can create a directory using the os module or the pathlib module. Here’s how to create a directory using both methods:

Using os module:
The os.mkdir() function creates a single directory. If the directory already exists, it raises an error. To avoid this, you can use os.makedirs() which creates intermediate directories as needed.

See also  Getting random numbers in Java

Example:
python
import os

# Create a single directory
os.mkdir(“new_directory”)

# Create intermediate directories if needed
os.makedirs(“parent_directory/new_directory”, exist_ok=True)

In this example, exist_ok=True prevents an error if the directory already exists.

Using pathlib module:
pathlib offers an object-oriented approach to handle file system paths. The Path class provides a mkdir() method to create directories.

See also  Difference Between Abstract Class and Interface in Java

Example:
python
from pathlib import Path

# Create a directory
path = Path(“new_directory”)
path.mkdir(exist_ok=True)

This method works similarly, and exist_ok=True ensures no error occurs if the directory exists

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Who is Sa Nguyen?

Helldivers

Who is ExtraEmily?

Recent Comments

0
Would love your thoughts, please comment.x
()
x