backspace
backspace

Reputation: 134

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 :)

Upvotes: 4

Views: 1676

Answers (1)

Masklinn
Masklinn

Reputation: 42492

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

Upvotes: 5

Related Questions