pathlib is a Python library that makes it easy to handle file in Python.
3.9.1. Create a New Directory and File¶
If you want to create new directories and files, you can either use os or pathlib. However, pathlib’s syntax is more straightforward and easier to understand than os’s syntax.
import os path = 'new' file = 'new_file.txt' # Create a new directory if not os.path.exists(path): os.makedirs(path) # Create new file inside new directory with open(os.path.join(path, file), 'wb'): pass
from pathlib import Path # Create a new directory folder = Path('new') folder.mkdir(exist_ok=True) # Create new file inside new directory file = folder / 'new_file.txt' file.touch()
new └── new_file.txt 0 directories, 1 file