1

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.

Joe
  • 575
  • 6
  • 24
  • Your question is not clear. What is the expected output when given `"mydir/myfile.txt"` ? The absolute path to the file `"C:/example/cwd/mydir/myfile.txt"` ? The relative path from the current dir to the file `"../mydir/myfile.txt"` ? Or is it a problem of "path separtor" (e.g. slashes `/` vs backslashes `\\`) ? – Lenormju May 27 '21 at 13:30
  • I want to get to `myfile.txt`. I want to type `"../mydir/myfile.txt"` instead of `"C:/example/cwd/mydir/myfile.txt"` so when I'll share my code, they can reuse my code without changing their directory because `"/mydir/myfile.txt"` is fixed. – Joe May 27 '21 at 16:42

2 Answers2

1

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)
Lenormju
  • 4,078
  • 2
  • 8
  • 22
  • Also, you mix forward slahes (`/`) and backward slashes (`\ `). The backward ones are used mainly on Windows, the others everywhere else. In general, it is better to not mix them up, it may cause your program to not work properly, or people to not understand your questions. – Lenormju May 28 '21 at 07:44
0

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?

State
  • 3
  • 4