Coding

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 scopy.py <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)
	print(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)):
						shutil.copy(
							os.path.join(folder, file),
							destination
						)
					
						#TODO:	print files copied (former path --> new path)
						print("File copied: {}".format(file))

else:
	print("Usage: python scopy.py <source> <destination> <extension>")



error: Content is protected !!