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.
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.)
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/.
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.
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With