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']
?
listdir(path='. ') It returns a list of all the files and sub directories in the given path. We need to call this recursively for sub directories to create a complete list of files in given directory tree i.e.
listdir() method in python is used to get the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned. Syntax: os.listdir(path)
One of the answers may be to use os. walk() to recursively traverse directories. The key here is to use os.
copy_tree . It works just fine and you don't have to pass every argument, only src and dst are mandatory. However in your case you can't use a similar tool like shutil. copytree because it behaves differently: as the destination directory must not exist this function can't be used for overwriting its contents.
import os [os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser("~/files")) for f in fn]
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