Monday 27 July 2020

Reading file using relative path in python project

from pathlib import Path

path = 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 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))

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

No comments:

Post a Comment