Python Learning: Automate Boring Stuff with Python | Chapter 8 : My Solution to Practice Project: Selective Copy

As usual… super simple automation..

I know it is quite trivial, but the fact that with a few lines of code I could re-organize my files based on their extensions makes coding really fun even outside of work. 



#selective copy
#walks through a folder tree and searches for files with a certain file extension.
#copies file matches into a new folder 

#Usage: python <source> <destination> <extension>

import sys, os, shutil

if len( sys.argv ) == 4:
#TODO: get source, destination and extension
	source = os.path.abspath(sys.argv[1])
	destination = os.path.abspath(sys.argv[2])
	extension = sys.argv[3]
#TODO: validate source and destination
	if not os.path.exists(source):
		print("Invalid source path")
	if not os.path.exists(destination):
		destination = os.mkdir(destination)
#TODO: loop through files and subfolders in source 
	for folder, subfolders, files in os.walk(source):
	#TODO: use shutil to copy files to destination
		for file in files:
			if file.endswith(extension):
					#only copy if file does not exist in destination 
					if not os.path.exists(os.path.join(destination, file)):
							os.path.join(folder, file),
						#TODO:	print files copied (former path --> new path)
						print("File copied: {}".format(file))

	print("Usage: python <source> <destination> <extension>")