Fixing '../../' paths in python

You can use os.path.realpath() to get the canonical path. To get a normalised relative path, use os.path.normpath().


You can use abspath in the os.path module.

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to normpath(join(os.getcwd(), path)).


If you are using the pathlib module, the method to use is resolve:

In [304]: print(p)
/group_workspaces/cems2/fiduceo/Users/gholl/logs/2016/08/10/srf_errorprop/../../../../../scratch/accidentally_deleted_shift_log

In [305]: print(p.resolve())
/group_workspaces/cems2/fiduceo/Users/gholl/scratch/accidentally_deleted_shift_log

Tags:

Python