Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.abspath('file1.txt') doesn't return the correct path

Tags:

python

path

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?

like image 519
Bentley4 Avatar asked Apr 05 '12 09:04

Bentley4


People also ask

What is OS path Expanduser?

path. expanduser() method in Python is used to expand an initial path component ~( tilde symbol) or ~user in the given path to user's home directory. On Unix platforms, an initial ~ is replaced by the value of HOME environment variable, if it is set.

What is OS path Abspath?

os.path. abspath (path) Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)) .

What is the use of OS path dirname (__ FILE __) in this method?

path. dirname() method in Python is used to get the directory name from the specified path.

What does OS path Dirname OS path Realpath (__ FILE __ do?

os. path. realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path") os.


2 Answers

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").

like image 73
orlp Avatar answered Sep 20 '22 03:09

orlp


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)).

like image 41
Per Fagrell Avatar answered Sep 22 '22 03:09

Per Fagrell