3.9. pathlib

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):

# Create new file inside new directory
with open(os.path.join(path, file), 'wb'):
from pathlib import Path

# Create a new directory
folder = Path('new')

# Create new file inside new directory
file = folder / 'new_file.txt'
!tree new 
└── new_file.txt

0 directories, 1 file