How to Get the Relative Path of a file in Python Program


If you have a relative path, i.e. the path relative to the current working directory for a Python Program or a Script and you want to reach the absolute path of a file(s), then you can get to it via the below steps,

  1. You should already be aware of the relative path of your file(s)
  2. Get the Path for the current working directory using os.getcwd()
  3. Join the current working directory path to your relative file path os.path.join() to get to the file(s)

Example:

import os

relative_data_file_path = "data_2023.csv"
relative_metadata_file_path = "meta/metadata_2023.csv"

working_dir_path = os.getcwd()

absolute_data_file_path = os.path.join(working_dir_path,relative_data_file_path)
absolute_metadata_file_path = os.path.join(working_dir_path,relative_metadata_file_path)

print(absolute_data_file_path)
print(absolute_metadata_file_path)

Output:

/Users/c2ctech/data_2023.csv
/Users/c2ctech/meta/metadata_2023.csv
How to get to Relative Path Files in Python
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap