Search code examples
pythonpython-3.xpathlib

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.


Solution

  • 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).