Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to normalize a relative path using pathlib

I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.

My python program is in the following folder:

G:\projects\code

I want to read this file which is one level up:

G:\projects\data\sales.csv

How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.

I tried this:

from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'

But now the 'file' variable equals this:

'G:/projects/code/../data/sales.csv'

I read through the docs and either it isn't explained there or I'm just missing it.

like image 845
Dread Avatar asked May 26 '19 13:05

Dread


2 Answers

Although it's not a problem that your path includes '..' (you can still use this path to open files, etc. in Python), you can normalize the path using resolve():

from pathlib import Path
path = Path.cwd() / '..' / 'data' / 'sales.csv'
print(path)  # WindowsPath('G:/projects/code/../data/sales.csv')
print(path.resolve())  # WindowsPath('G:/projects/data/sales.csv')

NB: I personally would name a variable that contains a path path, not file. So you could later on do file = open(path).

like image 53
wovano Avatar answered Sep 25 '22 20:09

wovano


print(
    Path(__file__).parent,  # the folder
    Path(__file__).parent.parent,  # the folder's parent
    sep='\n'
)

print(
    Path(
        Path(__file__).parent.parent, 'hello.py'
    )
)

results in

C:\Users\isik\Desktop\Python\MessAround\project\module
C:\Users\isik\Desktop\Python\MessAround\project
C:\Users\isik\Desktop\Python\MessAround\project\hello.py

with this file structure

-project
    -module
        -__init__.py
    -hello.py
    -__init__.py

while the code is located inside project.module.__init__.py

like image 37
Işık Kaplan Avatar answered Sep 23 '22 20:09

Işık Kaplan