Load File From Relative Path in PythonSep 17th 2021Words: 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
withopen("../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.