Coding

Python Learning: Automate Boring Stuff with Python | Making a directory and moving files into it

With this script we can make a new directory(if it does not exist) and move files with a given ending into the directory.

This was not a task in the book, but just something I thought of solving. Quite interesting to know what you could do with string operations like “startWith” and “endWith”.


#creates new directory and moves python script files into the newly created directory
#Usage python mvdir.py <ending> <source> <destination> <except>

import os, sys, shutil


#TODO: GET ENDING AND DESTINATION STRINGS 
if len( sys.argv ) >= 4:
	ending = sys.argv[1]
	source = sys.argv[2]
	destination = sys.argv[3]
	destination = os.path.abspath(destination)
	source = os.path.abspath(source)
	exception = None
	if len( sys.argv ) == 5:
		exception = sys.argv[4]
	#CREATE NEW DIRECTORY IF DOES NOT EXISTS ELSE JUST MOVE 
	if os.path.exists(source):
		if not os.path.exists(destination):
			os.mkdir(destination)
		for filename in os.listdir(source):
			if filename.endswith(  ending ) and exception not in filename:
				shutil.move(os.path.abspath(filename), destination )
				print("{} file was moved to {}".format(filename,   destination  ))
	else:
		print("Source does not exist")
else:
	print("Usage:  python mvdir.py <ending> <source> <destination> <except>")

#LIST ALL FILES AND MOVE ONLY THOSE ENDING WITH <ending>




error: Content is protected !!