User:Manetta/scripts/python-recursive-filesystem-loops

From XPUB & Lens-Based wiki
import os
import json
from pprint import pprint
# --> pprint = prettyprint!!! 

# ******************************************
# from: MICHAEL
# ******************************************

# f = os.listdir('.')
# print f

def processfolder(p):
	# function to loop through a nested folder structure, and 'save' all the files + correct paths in a dict
	# p = parameter of function

	out = {'path': p, 'files' : []}

	# out = {'path': p}
	# out['files'] = []

	for f in os.listdir(p):
		# 'listdir' is actually excecuting --> ls p (=dir) 
		fp = os.path.join(p, f)

		print 'p', p 
		# p = directory path

		print 'f', f
		# f = filename

		print "fp", fp
		# fp = filename + directory path

		if os.path.isdir(fp):
			#  isdir = is fp a folder, YES / NO 
			out['files'].append(processfolder(fp))

			# each folder will be again a dict element, they will be nested .. 
			# next to path then you could add the tags, the m-time, etc.

		else:
			out['files'].append(fp)

	return out

# calling the function:
# processfolder(".")

# pprint(processfolder("."))
# --> printing python dict (with 'prettyprint' --> indents the output)

print json.dumps(processfolder("."), indent=2)
# --> printing json file
# --> json.dumpS = json dump string
# --> json.dump = write into file



# ******************************************
# from: RUBEN
# ******************************************

def flatListFiles(p):
	# writing all filenames + paths to 1 (flat) list

	files = []
	
	for f in os.listdir(p):
		fp = os.path.join(p, f)

		if os.path.isdir(fp):
			# files.append(processfolder2(fp))
			files.extend(flatListFiles(fp))
			# append = creates a nested structure
				# --> now you need to create a nested loop (a recursive loop!)
			# extend = adds each item to one flat list
				# --> now you can loop through 1 flat list (unnested)
				#  sorts on ...??? what? nobody knows :), well....
		else:
			files.append(fp)

	files.sort()
	# sorts the list in every loop

	return files

print json.dumps(flatListFiles("."), indent=2)