How to get an absolute file path in Python? (Get rid of backslashes)

Viewed 1522

Given a path such as "mydir/myfile.txt", how do I find the file's absolute path relative to the current working directory in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt".

I tried: mypath = os.path.abspath("../mydir/myfile.txt"). But I got:

>> print(mypath)
C:\example\cwd\mydir\myfile.txt

Note that when I execute mypath I have C:\\example\\cwd\\mydir\\myfile.txt.

2 Answers

Based on your answer to my comment, what you want is to use a relative path to the file, not the absolute path to the file.
I recommend you to use os.path.relpath to compute the relative path from your current working directory to the file :

import os.path

# inputs
absolute_path_to_file = r"C:\example\cwd\mydir\myfile.txt"
current_working_directory = os.path.abspath(os.path.curdir)  # C:\example\cwd\my_other_dir

# using os.path.relpath
relative_path_from_current_working_directory_to_file = \
    os.path.relpath(absolute_path_to_file, current_working_directory)

# result
print(relative_path_from_current_working_directory_to_file)  # ..\mydir\myfile.txt

If you want, you can omit the second parameter to os.path.relpath (named start) because it defaults to your current directory (see os.curdir), so that you can simply do :

relative_path_from_current_working_directory_to_file = \
    os.path.relpath(absolute_path_to_file)

What would you expect instead of the C:\example\cwd\mydir\myfile.txt ?

What you see is an absolute Windows Filepath. Windows uses backslashes for its filepaths, while Linux resorts to forward slashes. The python os.path package automatically handles the conversion, thus although you enter a Linux-style path (at least almost, because Linux does not know about drives like C:), it automatically converts to Windows (as you run the code on a Windows machine).

Also see: What is the filepath difference between window and linux in python3?

Related