Saturday 18 April 2020

Reading file using relative path in python project

Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.
But there is an often used trick to build an absolute path from current script: use its __file__ special attribute:
import csv
import os.path

my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
    test = list(csv.reader(f))
Note, from python 3.4, __file__ is always absolute for imported modules and you can drop the os.path.abspath part in this example.
Better yet with python 3.4+, use the Path module as jpyams suggested in the comment below:
from pathlib import Path

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

from : https://stackoverflow.com/questions/40416072/reading-file-using-relative-path-in-python-project

No comments:

Post a Comment