Last active
August 29, 2015 14:01
-
-
Save atvKumar/e9971afa56e0a221f7dc to your computer and use it in GitHub Desktop.
listdir VS walk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def listLocation(root_location,files = [],folders = []): | |
""" A recursive function to get directory content into arrays | |
Usage : x,y = listLocation(directory/path) | |
Returns 2 arrays 1 files array and 1 folders array """ | |
for eachitem in os.listdir(root_location): | |
filePath = os.path.join(root_location,eachitem) | |
if os.path.isdir(filePath) and not eachitem.startswith('.'): | |
folders.append(filePath) | |
listLocation(filePath,files,folders) | |
elif os.path.isfile(filePath) and not eachitem.startswith('.'): | |
files.append(filePath) | |
elif os.path.islink(filePath): | |
pass | |
return files, folders |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def walklevel(some_dir, level=1): | |
some_dir = some_dir.rstrip(path.sep) | |
# assert path.isdir(some_dir) | |
num_sep = some_dir.count(path.sep) | |
for root, dirs, files in walk(some_dir): | |
yield root, dirs, files | |
num_sep_this = root.count(path.sep) | |
if num_sep + level <= num_sep_this: | |
del dirs[:] | |
def getFolders(location=None, subfolders=1): | |
return [i[0] for i in walklevel(location, subfolders)] | |
def getFiles(location=None, subfolders=2): | |
files = [i for i in walklevel(location, subfolders) if i[2] != []] | |
tmp = [] | |
for x in files: | |
for afile in x[2]: | |
tmp.append(path.join(x[0], afile)) | |
return tmp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment