Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding of python os.path.abspath

I have following code:

directory = r'D:\images' for file in os.listdir(directory):     print(os.path.abspath(file)) 

and I want next output:

  • D:\images\img1.jpg
  • D:\images\img2.jpg and so on

But I get different result:

  • D:\code\img1.jpg
  • D:\code\img2.jpg

where D:\code is my current working directory and this result is the same as

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

So, the question is: What is the purpose of os.path.abspath while I must use

os.path.normpath(os.path.join(directory, file)) 

to get REAL absolute path of my file? Show real use-cases if possible.

like image 279
Most Wanted Avatar asked Jul 11 '14 20:07

Most Wanted


2 Answers

The problem is with your understanding of os.listdir() not os.path.abspath(). os.listdir() returns the names of each of the files in the directory. This will give you:

img1.jpg img2.jpg ... 

When you pass these to os.path.abspath(), they are seen as relative paths. This means it is relative to the directory from where you are executing your code. This is why you get "D:\code\img1.jpg".

Instead, what you want to do is join the file names with the directory path you are listing.

os.path.abspath(os.path.join(directory, file)) 
like image 80
unholysampler Avatar answered Sep 20 '22 22:09

unholysampler


listdir produces the file names in a directory, with no reference to the name of the directory itself. Without any other information, abspath can only form an absolute path from the only directory it can know about: the current working directory. You can always change the working directory before your loop:

os.chdir(directory) for f in os.listdir('.'):     print(os.path.abspath(f)) 
like image 27
chepner Avatar answered Sep 22 '22 22:09

chepner