In Python, refereing a file with relative path could be troublesome, if the path is hard-coded like the following example:
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.
[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'
A safe way to use relative path for static file is to resolve it by the script path:
A patched exmaple:
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