Skip to content

Instantly share code, notes, and snippets.

@notalentgeek
Last active December 24, 2016 09:41
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/f4fc767f774c25afed59f506ef96b3a9 to your computer and use it in GitHub Desktop.
Save notalentgeek/f4fc767f774c25afed59f506ef96b3a9 to your computer and use it in GitHub Desktop.
Python automation script for initiating my notes.
# This is a Python script to initiate notes with all images.
# Images are all already re - sized into 600 pixel width with
# proportional height. First is that I need to get the directory
# that is filled with the notes I want to init.
import datetime as dt
import io
import os
import shutil
import subprocess
import sys
import time
def main(args):
startDir = sys.argv [1]
# Manual timezone.
manualTimeZone = sys.argv[2]
#print(startDir)
# After I can retrieve the starting directory I would like to
# list all available directories and files.
startDirList = os.listdir(startDir)
#print(startDirList)
# Create a temporary copy of the starting directory.
tempFolderName = "temp"
# Get the folder name of the startDir.
startDirNorm = os.path.normpath(startDir)
startDirBaseName = os.path.basename(startDirNorm)
#print(startDirBaseName)
# Full name of the temporary folder.
tempFolderNameFull = tempFolderName + "-" + startDirBaseName
# Get the 1 up parent directory.
parDir = startDir.split("/")
parDir.pop()
#print(parDir)
upDir = None
for s in parDir:
if upDir == None: upDir = s
else: upDir = upDir + "/" + s
#print(upDir)
# Construct absolute path for the temporary folder.
tempDir = os.path.join(upDir, tempFolderNameFull)
#print(tempDir)
# Check if the temporary directory is exists or not.
# If so delete the old temporary folder before this program
# creating a new temporary folder.
if os.path.exists(tempDir):
#print(os.path.exists(tempDir))
shutil.rmtree(tempDir)
# Create the temporary folder.
shutil.copytree(
startDir,
tempDir)
# Get list of all files and folders in the temporary folder.
tempDirList = os.listdir(tempDir)
#print(tempDirList)
# After I get the list of the directory then I proceed to remove
# any files from the tempDirList. I only want to deal with the
# note folder. tempDirListOnly is a variable that holds an array
# only for directory/folder in startDir, NO FILES.
tempDirListOnly = []
for f in tempDirList:
#print(f)
#print(os.path.isdir(f))
absolutePathToF = os.path.join(startDir, f)
#print(absolutePathToF)
#print(os.path.isdir(absolutePathToF))
if os.path.isdir(absolutePathToF): tempDirListOnly.append(f)
#print(tempDirListOnly)
# From the listed folders I need to change the name.
# Get the time informations.
for f in tempDirListOnly:
# Make an absolute path.
absPathForF = os.path.join(tempDir, f)
#print(absPathForF)
realName = ConstructRealName(f, absPathForF, manualTimeZone)
#print(realName)
absPathForFNew = os.path.join(tempDir, realName)
# Change the folder name.
shutil.move(absPathForF, absPathForFNew)
# Real name for files. There is no prefix "pending" in file
# name, only in folder.
realNameFile = realName.replace("pending-", "")
# What I need to do next is to create an markdown file for
# every directories/folder in tempDir. However first
# I need to construct proper name for the folder.
absPathToMD = os.path.join(absPathForFNew, realNameFile + ".md")
with io.FileIO(absPathToMD, "w") as md: pass
# Take a look what is inside the newly renamed directory.
# Especially those image files. Directory listing.
absPathForFNewLst = os.listdir(absPathForFNew)
#print(absPathForFNewLst)
# Lines for the markdown file.
lines = []
# Image index for naming convention.
imageIndex = 1
for fAgain in absPathForFNewLst:
# Absolute path for each files and folders in
# absPathForFNew.
fAgainPath = os.path.join(absPathForFNew, fAgain)
#print(absPathForFNew)
#print(fAgainPath)
# Check if there is a folder.
CheckIfThisIsAFolderThenStop(fAgainPath)
#print(fAgain)
# Check the extension here. Separate it based on
# image and non - image files.
fileName, fileExt = os.path.splitext(fAgain)
#print(fileExt)
# Proof that Python string comparison is case sensitive.
#print("jpg".lower() == "JPG".lower())
# An array of extensions that can be considered image that
# can be resized. The problem here is to rename all static
# .gif into either of these extension. For example a static
# .gif named my_static_gif.gif should be just named
# my_static_gif.png.
anArrayOfImageExts = [".bmp",
".jpeg", ".jpg", ".png"]
# Check if the file we are currently iterating is an image
# file or not. If fileIsAnImage is True then the file is an
# image.
fileIsAnImage = None
for ext in anArrayOfImageExts:
fileIsAnImage = False
# Python string comparison is case sensitive
# so I need to compare them as they are all in
# lower case or upper case letter.
# After the file is identified as an image escape
# from this loop.
if fileExt.lower() == ext.lower():
fileIsAnImage = True
break
#print(".jpg" == ".png")
#print(fileExt + " " + ext + " " + str(fileIsAnImage))
#print(fileExt.lower() + " " + ext.lower() + " " + str(fileIsAnImage))
#print(fileIsAnImage)
# Since there will no folder in this folder I can safely
# assume that every image makes image index increase.
# If the file is an image then resize and change its name.
if fileIsAnImage:
#print(fAgain)
#print(realName)
newImageName = realNameFile + "-" + str(imageIndex) + ".png"
imageIndex = imageIndex + 1
absPathToNewImageName = os.path.join(absPathForFNew, newImageName)
#print(newImageName)
#print(imageIndex)
#print(absPathToNewImageName)
## Use ImageMagick!
subprocess.call(["convert \"" + fAgainPath + "[600x]\" " +
absPathToNewImageName], shell=True)
print("processing " + fAgainPath + " to " + absPathToNewImageName)
# Remove the old image file.
os.remove(fAgainPath)
# Construct string for the markdown file.
# Construct new line in markdown file.
lines.append("![./" + newImageName +
"](./" + newImageName +")")
# Added 2 line breaks so that images are not
# in line with each other.
lines.append("\n")
lines.append("\n")
# Pop 2 line breaks at the last image.
lines.pop()
lines.pop()
# Write it into markdown file (overwrite).
with open(absPathToMD, "r+") as md:
md.writelines(lines)
# Function to check if there is at least a folder in side
# the directory.
def CheckIfThisIsAFolderThenStop(_absPathToFileOrFolder):
# If it is a folder then halt the program
# until the folder is deleted. The variable
# printOnce is only to make sure that the
# print() is only executed once for every folder
# found.
printOnce = False
while os.path.isdir(_absPathToFileOrFolder):
# Check if the folder has content(s).
# If the folder has content(s) then let the
# user delete it manually. If the folder has
# no content (for example it just an empty
# folder) then this program will delete it
# automatically.
fldrOrFlLst = os.listdir(_absPathToFileOrFolder)
if len(fldrOrFlLst) <= 0: shutil.rmtree(_absPathToFileOrFolder)
# The else statement is when there are folder
# with content in it.
else:
if not printOnce:
printOnce = True
print(
_absPathToFileOrFolder +
" is a folder and has content(s) please check and delete it manually!")
print("this program will progress automatically")
if printOnce: print("the progress continue")
# Function to construct name for the main folder
# according to my own convention.
def ConstructRealName(
_f,
_absPathToFileOrFolder,
_manualTimeZone
):
# Get the folder properties. For naming convention.
# In this case I want to get the creation time of the
# folder. The two lines below is to get the folder
# creation times.
creationTime = os.path.getctime(_absPathToFileOrFolder)
timeConvFromCTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(creationTime))
# I put x as a prefix because time variable is already taken.
# It has no meaning :D!
dateX = str(timeConvFromCTime).split(" ")[0]
timeX = str(timeConvFromCTime).split(" ")[1]
yearX = dateX.split("-")[0]
monthX = dateX.split("-")[1]
dayX = dateX.split("-")[2]
hourX = timeX.split(":")[0]
minX = timeX.split(":")[1]
#print(creationTime)
#print(timeConvFromCTime)
#print(dateX)
#print(timeX)
#print(yearX)
#print(monthX)
#print(dayX)
#print(hourX)
#print(minX)
# Construct the prefix name.
prefixName = (yearX + monthX + dayX + "-" +
hourX + minX + "-" + _manualTimeZone + "-")
#print(prefixName)
# Specific naming convention for pending folder.
if _f.split("-")[0] == "pending":
tempRealName = _f.replace("pending-", "")
#print(tempRealName)
realName = "pending-" + prefixName + tempRealName
else:
# Change the name of each folder.
# Construct the real name.
realName = prefixName + _f
#print(realName)
return realName
if __name__ == "__main__": main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment