• Home
  • Django
  • list all files and directories of given folder

list all files and directories of given folder

linkaiyi
Follow

list all files of a directory

os.listdir() will get you everything that’s in a directory - files and directories.

If you want just files, you could either filter this down using os.path:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

or you could use os.walk() which will yield 3-tuple (dirpath, dirnames, filenames) for each directory it visits. dirpath is the given root path, dirnames is the list of all subdirectories and filenames is the list of all files (non directories) . If you only want the top directory you can just break the first time it yields

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break
Object has 0 attachments

Was this article helpful?

This article is viewed 9 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support