Os.path.abspath ('file1.txt') does not return the correct path

Say the file1.txt file path is equal to /home/bentley4/Desktop/sc/file1.txt Say my current working directory/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')

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

So, this only works if I am in the same directory as an existing file or in a directory, in the same directory or more than the directory path of this file?

+5
source share
4 answers

os.path.abspath(filename) , . , .

/home/bentley4/Desktop/sc/file1.txt, /home/bentley4, os.path.abspath("Desktop/sc/file1.txt").

+11

abspath , .

:

(join (os.getcwd(), path)).

+1

os.path.abspath(__file__).

0

, cwd os.chdir(another_path), . another_path.
:

  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

All Articles