3

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

backspace
  • 124
  • 1
  • 9
  • Does this answer your question? [How to get an absolute file path in Python](https://stackoverflow.com/questions/51520/how-to-get-an-absolute-file-path-in-python) – AMC Feb 11 '20 at 20:13
  • In my view this shouldn't have been closed. Anyways try [os.path.normpath](https://docs.python.org/3/library/os.path.html#os.path.normpath). E.g. `os.path.normpath('./test') = 'test')`. (Thx @Green-Cloak-Guy) – Nic Scozzaro Aug 20 '21 at 07:31

1 Answers1

4

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

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • 3
    [Or, if absolutification is not required, `os.path.normpath` does literally exactly what the question wants](https://docs.python.org/3/library/os.path.html#os.path.normpath) – Green Cloak Guy Feb 11 '20 at 13:50