user2052436
user2052436

Reputation: 4765

OS-agnostic relative path using pathlib

I have a string variable dirname, that contains path with correct slashes ('/' if on Linux, '\' if on Windows).

And I have a relative filename string that may contain wrong slashes.

How do I join them and get a correct full filename for the OS, where I am running the script, using pathlib?

For example running on Linux:

dirname = '/users/myname/dir1'
filename1 = '..\\dir2\\file.txt'
filename2 = '../dir2/file.txt'

I want to join dirname with either filename1 or filename2, and get /users/myname/dir2/file.txt in both cases.

Running on Windows:

dirname = 'C:\\dir1'
filename1 = '..\\dir2\\file.txt'
filename2 = '../dir2/file.txt'

I want to join dirname with either filename1 or filename2, and get C:\\dir2\\file.txt in both cases.

Upvotes: 3

Views: 1334

Answers (1)

AMC
AMC

Reputation: 2702

A potential solution would be to store only the components of the path:

import pathlib

path_1 = pathlib.Path(r"/users/myname/dir1")
print(path_1)

path_list = ["dir2", "file.txt"]

path_2 = pathlib.Path(*path_list)
print(path_2)

res = path_1.joinpath(path_2)
print(res)

Output:

/users/myname/dir1
dir2/file.txt
/users/myname/dir1/dir2/file.txt

Unfortunately this isn't perfect, it seems that file paths can get quite messy. See for example cross-platform splitting of path in python. This answer is quite neat.

Upvotes: 2

Related Questions