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

Python strip with \n

You should be able to use line.strip('\n') and line.strip('\t'). But these don't modify the line variable...they just return the string with the \n and \t stripped. So you'll have to do something like
line = line.strip('\n')
line = line.strip('\t')
That should work for removing from the start and end. If you have \n and \t in the middle of the string, you need to do
line = line.replace('\n','')
line = line.replace('\t','')
to replace the \n and \t with nothingness.

from : https://stackoverflow.com/questions/9347419/python-strip-with-n