Hello I am new to python and have a question about the best/pythonic way to do nested loops.
I want to go put each directory in an array with a nested array of the file contained in a that directory.
I have been looking at pythons arrays, dicts, sets and tupples and not sure of the best way to do this
[ Note I just want to do this for one level not recursively through all directories ]
Currently I have a function that adds all the files of sub-directories to an array, but now I need to return their parent folder too.
Thanks in advance
def getffdirs():
filedirs = []
path = os.curdir
for d in os.listdir(path):
if os.path.isdir(d):
print("Entering " + d)
curPath = os.path.join(path, d)
for f in os.listdir(curPath):
if os.path.isfile(f):
print("file " + f)
filedirs.append(f)
return filedirs
2 Answers 2
i'd use a dictionary for this purpose, the keys would be directories and the values lists of files:
def getffdirs():
dirs = {}
path = os.curdir
for d in os.listdir(path):
if os.path.isdir(d):
print("Entering " + d)
dirs[d] = [] # add directory with empty list
curPath = os.path.join(path, d)
for f in os.listdir(curPath):
if os.path.isfile(f):
print("file " + f)
dirs[d].append(f) # add files to appropriate directory
return dirs
to access the data:
for dir,files in dirs.items(): # notice the call to dirs.items(), thats what was missing.
print "directory: ",dir
print "files:"
for f in files:
print f
1 Comment
EDIT: If you want a dictionary,
EDIT 2: If you want to omit hidden directories,
from os import listdir, curdir
from os.path import isfile, isdir, join
filedirs = dict((d, [f for f in listdir(d) if isfile(join(d,f))])
for d in listdir(curdir) if isdir(d) and d[0] != '.')
Original:
Is this what you're looking for?
filedirs = [[f for f in os.listdir(d) if os.path.isfile(os.path.join(d,f))]
for d in os.listdir('.') if os.path.isdir(d)]
os.walkis the only correct solution. One level or 100 levels.os.walkwill return agenerator object(very cool/efficient python tool) For examplefoo = os.walk()to get thegenerator objectandlevelOne = foo.next()for the first level list. Two lines of code... not bad.