Just Use Pathlib

edit ✏️

Pathlib is an amazing cross-platform path tool.

Import

from pathlib import Path

Create path object

Current Directory

cwd = Path('.').absolute()

Users Home Directory

home = Path.home()

module directory

module_path = Path(__file__)

Others Let's create a path relative to our current module.

data_path = Path(__file__) / 'data'

Check if files exist

Make Directories

data_path.mkdir(parents=True, exists_ok=True)

rename files

Path(data_path /'example.csv').rename('real.csv')

List files

Glob Files

data_path.glob('*.csv')

recursively

data_path.rglob('*.csv')

Write

Path(data_path / 'meta.txt').write_text(f'created on {datetime.datetime.today()})


Socials