Aleksander  Sołop Aleksander Sołop - 2 years ago 203
Python Question

How to get list of files in directory with full path to file

I need to get list of files which directory contains, but not only filename, but list of full paths to the file. Like in archive I can do:

tar = tarfile.open(directory, "r:gz")
directory_to_get_stuff_from = [member.name for member in tar.getmembers()]


But in usual directory I only can to get list of file names:

directory_to_get_stuff_from = os.listdir(directory)


How to get list of all available paths in directory and directories which main dir contains?

Answer Source

You could use os.path.join in order to get absolute filenames:

[os.path.join(directory, f) for f in os.listdir(directory)]

Notes

  • os.listdir doesn't recursively look for files in subfolders.
  • os.listdir returns files as well as directories inside directory.
  • You could use os.walk if you need more functionality.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download