Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute paths of all files in a directory

How do I get the absolute paths of all the files in a directory that could have many sub-folders in Python?

I know os.walk() recursively gives me a list of directories and files, but that doesn't seem to get me what I want.

like image 932
madCode Avatar asked Mar 22 '12 05:03

madCode


People also ask

How do you get the paths of all files in a folder in Python?

os. listdir() returns everything inside a directory -- including both files and directories. A bit simpler: (_, _, filenames) = walk(mypath). next() (if you are confident that the walk will return at least one value, which it should.)

How do I find the absolute path of a directory?

To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.

Does OS Listdir return full path?

Use os. listdir() function! We'll make a function for this, which simply gets the full path, and returns a list of all such names.

How do I list the full path of a file in Linux?

The answer is the pwd command, which stands for print working directory. The word print in print working directory means “print to the screen,” not “send to printer.” The pwd command displays the full, absolute path of the current, or working, directory.


2 Answers

os.path.abspath makes sure a path is absolute. Use the following helper function:

import os  def absoluteFilePaths(directory):     for dirpath,_,filenames in os.walk(directory):         for f in filenames:             yield os.path.abspath(os.path.join(dirpath, f)) 
like image 102
phihag Avatar answered Sep 19 '22 12:09

phihag


If the argument given to os.walk is absolute, then the root dir names yielded during iteration will also be absolute. So, you only need to join them with the filenames:

import os  for root, dirs, files in os.walk(os.path.abspath("../path/to/dir/")):     for file in files:         print(os.path.join(root, file)) 
like image 34
wim Avatar answered Sep 18 '22 12:09

wim