37

I'd like to get a list of all files in a directory recursively, with no directories.

Say there's a directory ~/files with "a.txt", "b.txt", and a directory "c" with "d.txt" and "e" inside it, and "f.txt" inside e. How would I go about getting a list that looks like ['/home/user/files/a.txt', '/home/user/files/b.txt', '/home/user/files/c/d.txt', '/home/user/files/c/e/f.txt']?

tkbx
  • 15,602
  • 32
  • 87
  • 122
  • The paths to `d.txt` and `f.txt` that you specified don't exist, so... – roippi Oct 11 '13 at 03:16
  • See the second answer in the following and just remove the print dir_names http://stackoverflow.com/questions/4918458/how-to-traverse-through-the-files-in-a-directory – davecom Oct 11 '13 at 03:18
  • Downvoted for being a FAQ –  Oct 11 '13 at 04:31
  • The answer that was a duplicate was about os.walk and glob.glob. So, those don't answer this question. This question is about os.listdir. Why? Because tests show os.listdir as creating a list of files faster than os.walk and glob.glob. Thanks. – Debug255 Oct 03 '18 at 16:30

1 Answers1

82
import os
[os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser("~/files")) for f in fn]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502