Fork me on GitHub

axju

Just coding stuff

Python Pathlib


For a long time I ignore pathlib, but then came new django release with this in the default settings.

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

I researched and found these links very helpful:

For more information check this out. I don't want to explain it in detail, just give an example.

Everything is an object

The old days I uses the os.path module to work with paths. To check if a file exist I run this:

>>> import os
>>> path = 'pyth/to/my/file'
>>> os.path.isfile(path)
False

There the path is a string. With the new pathlib module, you can creates a path object with some nice functions.

>>> import pathlib
>>> path = pathlib.Path('path/to/my/file')
>>> path.exists()
False

The path object has more than just the function exist(). You can do everything similar to the os.path module and more.

Example

This create the folder .axju in your home folder and the file data.txt with the content hello.

With pathlib:

from pathlib import Path

data_file = Path.home() / '.axju' / 'data.txt'
data_file.parent.mkdir(parents=True, exist_ok=True)

with data_File.open('w') as file:
    file.write('hello')

With os.path:

import os

home = os.path.expanduser('~')
home_axju_dir = os.path.join(home, '.axju')
if not os.path.exists(home_axju_dir):
    os.makedirs(home_axju_dir)

with open(os.path.join(home_axju_dir, 'data.txt'), 'w') as file:
    file.write('hello')