Reading file using relative path in python project Reading file using relative path in python project python python

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:

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

This requires python 3.4+ (for the pathlib module).

If you still need to support older versions, you can get the same result with:

import csvimport os.pathmy_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))

[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]


For Python 3.4+:

import csvfrom pathlib import Pathbase_path = Path(__file__).parentfile_path = (base_path / "../data/test.csv").resolve()with open(file_path) as f:    test = [line for line in csv.reader(f)]


This worked for me.

with open('data/test.csv') as f: