Load File From Relative Path in Python Sep 17th 2021 Words: 151

Problem

In Python, refereing a file with relative path could be troublesome, if the path is hard-coded like the following example:

1
2
3
4
import csv

with open("../data/test.csv") as f:
test = [line for line in csv.reader(f)]

When executing the file, the relative path is resolved with the current working directory, so if the script is running with a different working directory, relative path could be broken.

1
2
3
4
5
6
[email protected]:/your/working/dir/$ python /project/path/main.py

Traceback (most recent call last):
...
...
FileNotFoundError: [Errno 2] No such file or directory: '../data/test.csv'

Solution

A safe way to use relative path for static file is to resolve it by the script path: __file__

A patched exmaple:

1
2
3
4
5
from pathlib import Path

path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
test = list(csv.reader(f))

To convert the Path object to str, just use str() method