简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM