6
votes

Say the path of the file 'file1.txt' is /home/bentley4/Desktop/sc/file1.txt Say my current working directory is /home/bentley4

import os
os.path.abspath('file1.txt')

returns /home/bentley4/file1.txt

os.path.exists('file1.txt')

returns False. If I do

os.path.abspath('file_that_does_not_exist.txt')

It returns /home/bentley4/file_that_does_not_exist.txt But again, this is not correct. The file does not even exist on my computer. Is there a way to get the correct absolute path from any directory I am currently working in? (aside from defining a new function)

So this only works when I am in the same directory as the existing file or in the directory one directory or more further from the path of the directory of that file?

5
That's quite curious, os.path.abspath should just work. What does os.getcwd() return? ... Oh, d'oh, hang on, you're saying that you're in /home/bentley4 and you're expecting os.path.abspath to somehow find a file in a sub-directory thereof? It doesn't do that. - torek
What are you trying to do? Are you trying to find a file by name in any of the sub-directories of your current working directory? - Chris Wesseling

5 Answers

13
votes

os.path.abspath(filename) returns an absolute path as seen from your current working directory. It does no checking whether the file actually exists.

If you want the absolute path of /home/bentley4/Desktop/sc/file1.txt and you are in /home/bentley4 you will have to use os.path.abspath("Desktop/sc/file1.txt").

1
votes

abspath just builds a path, it doesn't check anything about files existing.

From the docs:

On most platforms, this is equivalent to normpath(join(os.getcwd(), path)).

0
votes

You will get the path with os.path.abspath(__file__).

0
votes

The problem should be that previously the cwd was changed using the os.chdir(another_path) and it's still loaded in the context of the current execution. so the fix should be restore the original path after the use of the task in another_path has finish.
Example :

  original_path = os.getcwd()
  os.chdir(another_path) 
  # here perform some operation over another_path
  os.chdir(original_path ) # here is the restore of the original path
0
votes

I was working on the same issue and I found this, hope it helps you:

os.path.join(root, f)