With this script we can make a new directory 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    

import os
import sys
import 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) and os.path.isdir(source):
        if not os.path.exists(destination):
            os.mkdir(destination)
        for filename in os.listdir(source):
            if filename.endswith(ending):
                #LIST ALL FILES AND MOVE ONLY THOSE ENDING WITH 
                if exception == None or (exception and exception not in filename):
                    shutil.move(os.path.abspath(filename), destination)
                    print("{} file was moved to {}".format(
                        filename, destination))
                else:
                    print("File {} was not moved".format(filename))
            else:
                print("File {} does not end with {}".format(filename, ending))
    else:
        print("Source does not exist")
else:
    print("Usage: python mvdir.py    ")

%d bloggers like this: