Python Convert Relative to Absolute File Path

Kontext Kontext 0 5594 5.43 index 9/4/2022

Code description

This code snippet shows you how to convert a relative path to absolute path using os module in Python and vice versa. 

We utilize os.path.abspath and os.path.relpath functions. For the later, it accepts the second parameter as the base path which will be used to calculate the relative path.

Output:

*The current directory when running this code is C:\Users\userid.

C:\Users\test.csv
..\test.csv

Code snippet

    import os
    relative_path = "../test.csv"
    absolute_path = os.path.abspath(relative_path)
    print(absolute_path)
    print(os.path.relpath(absolute_path, "C:\\Users\\myfolder"))
    
python

Join the Discussion

View or add your thoughts below

Comments