Skip to content

Instantly share code, notes, and snippets.

@notalentgeek
Last active December 25, 2016 20:14
Show Gist options
  • Save notalentgeek/88359e3e2638d2edccaf3c0d4271f0c6 to your computer and use it in GitHub Desktop.
Save notalentgeek/88359e3e2638d2edccaf3c0d4271f0c6 to your computer and use it in GitHub Desktop.
Python automation script for managing my personal "see" folder.
from os import listdir
from os.path import isfile, join
from tzlocal import get_localzone
import datetime as dt
import os
import shutil
import sys
# Constants.
# Constant for a backup folder name.
BACKUP = "backup"
# Constant for temporary folder name.
TEMP = "temp"
# Arguments from script execution.
# Starting directory that want to
# be managed.
startDir = str(sys.argv[1])
# Target directory that want to be
# managed into.
targetDir = str(sys.argv[2])
# Specific name for the moved files.
specName = str(sys.argv[3])
# Some variables that need to be
# initiated globally.
# Variable that hold absolute path
# to the backup directory.
backupDir = None
# The main name for each of the files.
mainName = None
def main(args):
print("initializing....")
print("please do not modify the folder this program process until it finish")
# Print argument variables.
#print(startDir)
#print(targetDir)
#print(specName)
# Assign global variables.
global specName
global mainName
# Variable to contain absolute path
# to the temporary folder temp. At
# this point the temp folder is not
# yet created.
tempDir = join(startDir, TEMP)
# Edit the spec name.
# If there is no specName provided.
# Blank string then put specName as "".
specName = "" if specName == "" else "-" + specName
# The main name for each moved files
# is the folder name of the target
# directory.
# Normalize the target directory path
normalPath = os.path.normpath(targetDir)
# Take the target directory folder name.
pathBaseName = os.path.basename(normalPath)
# Construct the mainName for each files
# that will be moved from the starting
# directory into the target directory.
mainName = pathBaseName.lower() + "-"
#print(tempDir)
#print(normalPath)
#print(pathBaseName)
#print(mainName)
# List all items in the starting directory.
listStartDir = []
for f in listdir(startDir):
if os.path.isfile(join(startDir, f)):
listStartDir.append(f)
# List all items in the target directory.
# This will be used to know the starting
# of the moved files.
listTargDir = []
for f in listdir(targetDir):
if os.path.isfile(join(targetDir, f)):
listTargDir.append(f)
# Count those files!
totFilesInStartDir = len(listStartDir)
totFilesInTargDir = len(listTargDir)
#print(listStartDir)
#print(listTargDir)
#print(totFilesInStartDir)
#print(totFilesInTargDir)
# Before doing anything harm. Let us
# create a backup folder first in the
# target directory.
CreateBackupInTarget()
# Create a temporary folder named temp
# in the starting directory.
if os.path.exists(tempDir): shutil.rmtree(tempDir)
os.makedirs(tempDir)
# Do backup in the target directory.
index = 1
for f in listTargDir:
# Absolute path to the file that wants
# to be moved into the backup folder
# from the starting directory.
mainFile = join(targetDir, f)
# Absolute path to the file location
# in the backup folder.
backupFile = join(backupDir, f)
# Check if f is a folder or not.
# We do not want to backup folder
# but files.
if not os.path.isdir(mainFile):
# Backup!
shutil.copy2(
mainFile, backupFile)
# This is for the user to know
# this backup progress.
print(
"backup " +
str(index) + "/" +
str(totFilesInTargDir))
# The index variable is just for the user
# know the progress of this backup.
index = index + 1
# Copy all files from the starting directory into
# the temporary folder. Then copy files from the
# temporary directory into the target directory.
index = 1
for f in listStartDir:
#print(f)
# Absolute path to the file that will be
# moved into the target directory.
mainFile = join(startDir, f)
# Absolute path to the copied file destined
# directory.
copiedFile = join(tempDir,f)
# Get the file extension of the f. And then
# added the extension into ConsFileName()
# function so that the new file will have
# an extension.
fileName, fileExt = os.path.splitext(f)
# Absolute path to the copied file destined
# directory with the file name all in lower
# case.
copiedFileLower = join(tempDir, f.lower())
#print(copiedFileLower)
# Make sure we do nothing on the folders.
# In this program we will only deal with
# files.
if not os.path.isdir(mainFile):
# Edit the file extension a bit.
# Make sure that there is no upper
# case letters and make sure to
# convert .jpeg into .jpg.
fileExt = fileExt.lower()
fileExt = ".jpg" if fileExt == ".jpeg" else fileExt
# Construct new name for the files
# those are moved into the target
# directory.
newName = ConsFileName(
totFilesInTargDir + index, fileExt)
# Absolute path to the moved file
# in the target directory with its
# new name.
destinedPath = join(targetDir, newName)
# Copy the file from the starting
# directory into the temporary directory.
shutil.copy2(mainFile, copiedFile)
# Change the file name into all lower
# case (including the extension name).
shutil.move(copiedFile, copiedFileLower)
# Move the file into the target directory.
# With new file name.
shutil.move (
copiedFileLower, destinedPath)
# This print() is only for the user know
# the move progress.
print(
"moving " +
str(index) + "/" +
str(totFilesInStartDir))
# The index variable is just for the user
# know the progress of this backup.
index = index + 1
# Remove the temporary folder.
shutil.rmtree(tempDir)
# Function that returns a string for
# the new name of the move file.
def ConsFileName(_count, _ext):
return str(
mainName +
str(_count) +
specName +
_ext)
# Function to create a backup folder in the
# starting directory.
def CreateBackupInTarget():
# Assign global reference into the
# backup directory.
global backupDir
# Get the current date and time.
crntDT = GetDateTime()
year = crntDT[0]
month = crntDT[1]
day = crntDT[2]
hour = crntDT[3]
minu = crntDT[4]
sec = crntDT[5]
utc = crntDT[6]
# Construct the date string.
dateString = year + month + day
# Construct the time string.
timeString = hour + minu + sec
# Construct the time zone string.
if utc.split("/")[1] == "amsterdam":
tZone = "gmt+2"
# Construct the backup folder name.
bckDirName = (
dateString + "-" +
timeString + "-" +
tZone + "-" +
BACKUP)
# Assign the string of the absolute path
# to the backup directory into backupDir
# variable.
backupDir = join(targetDir, bckDirName)
# Check if the backup folder is already exist
# or not.
if os.path.exists(backupDir): shutil.rmtree(backupDir)
os.makedirs(backupDir)
def GetDateTime():
# Set up the strings.
# Date and time.
dateTime = str(dt.datetime.utcnow()).split(".")[0]
date = str(dateTime).split(" ")[0]
time = str(dateTime).split(" ")[1]
year = str(date).split("-")[0]
month = str(date).split("-")[1]
day = str(date).split("-")[2]
hour = str(time).split(":")[0]
minu = str(time).split(":")[1]
sec = str(time).split(":")[2]
# UTC time zone (without DST).
utc = str(get_localzone()).lower()
# Setup array for return.
returnArray = [
year,
month,
day,
hour,
minu,
sec,
utc
]
return returnArray
if __name__ == "__main__": main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment