Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ../ or ./ from file path

I have a path to a file and a path to a directory. The file is supposed to be somewhere (multiple levels) in that directory. I want to compare the beginning of the path to the file with the path to the directory. So what I basically do is:

if file_path.startswith(directory_path):
    do_something()

Both paths are strings. Unfortunately, my path to the file includes ".." and ".". So it looks something like this: /home/user/documents/folder/../pictures/house.jpg. As the other path does not contain those dots, the comparison fails, obviously. Is there a way in python to remove those spots from the string? I thought of using path.join() from the os module, which did not work. Thanks a lot for any help :)

like image 383
backspace Avatar asked Oct 19 '25 07:10

backspace


1 Answers

Is there a way in python to remove those spots from the string? I thought of using path.join() from the os module, which did not work. Thanks a lot for any help :)

os.path.abspath will normalise the path and absolutify it. Alternatively, pathlib.Path.resolve().

like image 77
Masklinn Avatar answered Oct 20 '25 20:10

Masklinn