Skip to content

Instantly share code, notes, and snippets.

@notalentgeek
Last active December 25, 2016 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notalentgeek/e14a701db8243aba6789781dbc9c464a to your computer and use it in GitHub Desktop.
Save notalentgeek/e14a701db8243aba6789781dbc9c464a to your computer and use it in GitHub Desktop.
Python script to arrange numbering in my "see" folder.
# Python script to arrange files numbering in my personal see folder.
from tzlocal import get_localzone
import datetime as dt
import os
import shutil
import sys
def ArrangeFilesNumbering(_startDir):
# Get the list of files and folders in
# the starting directory.
startDirList = os.listdir(_startDir)
#print(startDirList)
# Create backup.
backupDir = CreateBackupInDir(_startDir)
# This variable below is used to
# store all files in the starting
# directory without any directories/
# folders.
startDirLstWithoutFolders = []
# Get the one upper directory because it
# is serve as the main name of these files.
getMainName = _startDir.split("/")
# The one upper name would be the last index
# from the above _startdir.split("/").
getMainName = getMainName[len(
getMainName) - 1]
# Put all files (without folder)
# into the startDirLstWithoutFolders.
for fileOrFolder in startDirList:
# Get the absolute path of the
# fileOrFolder.
absPathToFileOrFolder = os.path.join(
_startDir, fileOrFolder)
#print(absPathToFileOrFolder)
# If file or folder is not a directory
# then put it into the
# startDirLstWithoutFolders list.
if not os.path.isdir(
absPathToFileOrFolder):
startDirLstWithoutFolders.append(
fileOrFolder)
print(len(startDirLstWithoutFolders))
# Copy into the backup folder.
backupCounter = 1
for files in startDirLstWithoutFolders:
# Absolute path into the file.
absPathToFileIWantToBackup = os.path.join(_startDir, files)
# Absolute path into the backup file.
absPathToFileIHaveBackup = os.path.join(backupDir, files)
#print(absPathToFileIHaveBackup)
# Backup it!
shutil.copy2(absPathToFileIWantToBackup,
absPathToFileIHaveBackup)
print("backup count: " +
str(backupCounter) + "/" +
str(len(startDirLstWithoutFolders)))
backupCounter = backupCounter + 1
# Iterate through all files. I am using while
# loop here so that I can control the indexing.
fileIndex = 0
while fileIndex < len(
startDirLstWithoutFolders):
# Get the current file numbering.
getCurrentFileNumber = GetFileNumberIndex(
getMainName,
startDirLstWithoutFolders,
fileIndex)
getPreviousFileNumber = None
# Get the previous file numbering if
# the fileIndex is not 0.
if fileIndex > 0:
getPreviousFileNumber = (
GetFileNumberIndex(getMainName,
startDirLstWithoutFolders,
(fileIndex - 1)))
# Compare the current file numbering
# and the previous index file
# numbering. This is why the file
# numbering needs to be converted into
# integer.
if not getPreviousFileNumber == None:
if getCurrentFileNumber > getPreviousFileNumber:
print(str(getCurrentFileNumber) +
">" + str(getPreviousFileNumber))
pass
if getCurrentFileNumber < getPreviousFileNumber:
print(str(getCurrentFileNumber) +
"<" + str(getPreviousFileNumber))
pass
# Keep looping and moving back to
# index if the previous file numbering
# is bigger than the current file
# numbering. Do not forget to reduce
# the current index for every swap.
while (getCurrentFileNumber <
getPreviousFileNumber):
# If the current file number
# is smaller then the previous
# index file number then we need
# to keep swapping back until
# the current file number is
# bigger than its previous
# index file number. These
# codes below is to swapping
# elements in a list.
(startDirLstWithoutFolders[
fileIndex],
startDirLstWithoutFolders[
fileIndex - 1]) = (
startDirLstWithoutFolders[
fileIndex - 1],
startDirLstWithoutFolders[
fileIndex])
# If an element swapped one back
# then reduce the fileIndex.
fileIndex = fileIndex - 1
# Get back the current file
# number and the previous
# index file number.
#
# Get the current file numbering.
getCurrentFileNumber = (
GetFileNumberIndex(
getMainName,
startDirLstWithoutFolders,
fileIndex))
# Previous index file numbering.
if fileIndex > 0:
getPreviousFileNumber = (
GetFileNumberIndex(getMainName,
startDirLstWithoutFolders,
(fileIndex - 1)))
else: getPreviousFileNumber = None
fileIndex = fileIndex + 1
# Now the files is sorted accordingly in
# startDirLstWithoutFolder array.
for sortedFile in startDirLstWithoutFolders:
#print(sortedFile)
# Get the absolute path!
absPathToSortedFile = os.path.join(
_startDir, sortedFile)
#print(absPathToSortedFile)
# I want to know the comparison
# between the sortedFile and its index.
#print(sortedFile + " " +
# str(startDirLstWithoutFolders.index(sortedFile) + 1))
# So what I need to know is to change
# the file number into the index.
currentFileNumber = GetFileNumberFileName(getMainName,
sortedFile)
#print(currentFileNumber)
# Add 1 because we start from 1 and not 0.
supposedFileNumber = str(
startDirLstWithoutFolders.index(sortedFile) + 1)
#print(str(currentFileNumber) + " " + str(supposedFileNumber))
# Before constructing new name I need to know
# the main name and the specific name.
forThisOperationMainName = sortedFile.split(str(currentFileNumber))[0]
forThisOperationSpecificName = sortedFile.split(str(currentFileNumber))[1]
theSupposedFileName = (forThisOperationMainName +
str(supposedFileNumber) + forThisOperationSpecificName)
#print("crnt file name: " + sortedFile)
#print("spsd file name: " + theSupposedFileName)
# Make the absolute path into theSupposedFileName.
absPathToSupposedFile = os.path.join(_startDir, theSupposedFileName)
#print(absPathToSupposedFile)
# Finally rename it from ascending to prevent conflicting
# file name.
shutil.move(absPathToSortedFile, absPathToSupposedFile)
# Function to create a backup folder in the
# starting directory.
def CreateBackupInDir(_dir):
# 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 = os.path.join(_dir, bckDirName)
# Check if the backup folder is already exist
# or not.
if os.path.exists(backupDir): shutil.rmtree(backupDir)
os.makedirs(backupDir)
return 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
# Here is a similar function to GetFileNumberIndex.
# But instead of using index I am going to use the
# file string instead.
def GetFileNumberFileName(_mainName, _fileName):
# Remove the main name from the file name.
fileNumber = _fileName.replace(_mainName + "-", "")
fileNumber = fileNumber.split("-")[0].split(".")[0]
fileNumber = int(fileNumber)
return fileNumber
# Here is a function to find the file numbering.
# The file numbering here is not the file index
# but the number in the file name itself.
def GetFileNumberIndex( _mainName,
_startDirArrayWithoutFolders,
_index):
# Get the current file numbering.
# Remove the main name. After the main
# name is removed (replaces with "") then
# the next characters before next "-" will
# be the file numbering.
#
# PENDING - 1 - DONE: Would be good if the only
# argument would be only the main name and
# the file name. So no array, because array
# will be processed outside of this function.
getNumber = _startDirArrayWithoutFolders[
_index].replace(_mainName + "-", "").split(
"-")[0].split(".")[0]
#print(_startDirArrayWithoutFolders[_index])
#print(_mainName)
#print(getNumber)
# Currently the number will be in string.
# Hence, cast it into integer!
#print(getNumber)
getNumber = int(getNumber)
return getNumber
if __name__ == "__main__":
ArrangeFilesNumbering(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment