To create a new folder (directory) in Python, you can use the os
or pathlib
modules.
- Using
os.mkdir()
:
python
import os
os.mkdir('new_folder') # Creates a new folder named 'new_folder'
- Using
pathlib.Path.mkdir()
(Python 3.5+):
python
from pathlib import Path
Path('new_folder').mkdir() # Creates a new folder named 'new_folder'
If you need to create intermediate directories, use os.makedirs()
or Path.mkdir(parents=True)
:
python
os.makedirs('parent_folder/new_folder') # Creates parent folder if needed
# or
Path('parent_folder/new_folder').mkdir(parents=True)
These methods create a directory at the specified path.