Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! python3
- import os
- import re
- import shelve
- import csv
- import datetime
- import shutil
- import logging
- import sys
- import subprocess
- m = datetime.datetime.today()
- mo = str(m.month)
- colPath = 'E://College'
- confPath = 'E://College//config'
- lbPath = 'E://College//University of the Philippines Los Baños'
- os.chdir(colPath)
- logging.basicConfig(filename=f'{confPath}//logsFA2.txt', level=logging.DEBUG,
- format='%(asctime)s - %(levelname)s - %(message)s',
- datefmt='%Y-%m-%d %H:%M:%S')
- fileReg = re.compile(r'''(
- ^([a-zA-Z0-9]*) #Classcode
- ([.]) #seperator
- ([. a-zA-Z0-9,]*) #Name of the File
- (\.docx | \.xlsx | \.pptx | \.pub | \.jpeg | \.png | \.jpg | \.psd | \.\w+)$ #File Extension
- )''', re.VERBOSE | re.IGNORECASE | re.DOTALL)
- listFile = os.listdir(colPath)
- listMatch = 0
- def checker():
- global listMatch
- sCode = shelve.open('E://College//config//config')
- for i in listFile:
- for groups in fileReg.findall(i):
- if groups[1] in sCode:
- listMatch += 1
- sCode.close()
- if listMatch is not 0:
- return True
- else:
- return False
- def writer(code, fid, name,path):
- global m
- with open(f'{confPath}//lists//{code}.csv', 'a', newline='') as csvfile:
- filewriter = csv.writer(csvfile, delimiter=',')
- date = m.strftime("%d-%m-%Y %H:%M:%S")
- filewriter.writerow([fid,f"{name}", f"{path}", date])
- def csvCounter(code):
- lineCount = 0
- if os.path.exists(f'{confPath}//lists//{code}.csv') is True:
- with open(f'{confPath}//lists//{code}.csv') as csvfile:
- lineCount = (len(list(csvfile)))
- elif os.path.exists(f'{confPath}//lists//{code}.csv') is not True:
- with open(f'{confPath}//lists//{code}.csv', 'wb') as csvfile:
- filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
- return lineCount
- def dirChecker(folder, ext):
- sCode = shelve.open('E://College//config//config')
- if os.path.exists(f"{lbPath}//{folder}//{sCode['months'][mo]}//{ext}") is not True:
- path = f"{lbPath}//{folder}//{sCode['months'][mo]}//{ext}"
- os.makedirs(path)
- sCode.close()
- def move():
- fMoved = 0
- sCode = shelve.open('E://College//config//config')
- if checker() is True:
- logging.info('Initiated moving session.')
- for y in listFile:
- for groups in fileReg.findall(y):
- if groups[1] in sCode:
- fileNum = csvCounter(sCode[groups[1]]) + 1
- newFileName = f'{groups[3]}{groups[4]}'
- if groups[4] in sCode:
- dirChecker(f'{sCode[groups[1]]}', f'{sCode[groups[4]]}')
- newFilePath = f"{lbPath}//{sCode[groups[1]]}//{sCode['months'][mo]}//{sCode[groups[4]]}//{newFileName}"
- try:
- shutil.move(groups[0], newFilePath)
- except PermissionError:
- logging.warning(f'Skipped {groups[0]} due to opened file.')
- else:
- writer(sCode[groups[1]], fileNum, f'{newFileName}', f'{newFilePath}')
- logging.info(f'[{groups[1]}]Filename {groups[0]} was moved, ID {fileNum}.')
- fMoved += 1
- elif groups[4] not in sCode:
- newFilePath = f"{lbPath}//{sCode[groups[1]]}//{sCode['months'][mo]}//{newFileName}"
- try:
- shutil.move(groups[0], newFilePath)
- except PermissionError:
- logging.warning(f'Skipped {groups[0]} due to opened file.')
- else:
- writer(sCode[groups[1]], fileNum, newFileName, newFilePath)
- logging.info(f'[{sCode[groups[1]]}]Filename {groups[0]} was moved, ID {fileNum}.')
- fMoved += 1
- if fMoved is not 0:
- logging.info(f'A total of {fMoved} was moved.')
- elif fMoved is 0:
- logging.info(f'No unopened files were moved')
- else:
- logging.warning('No file matched the subject codes.')
- sCode.close()
- def logOpen():
- logging.info(f'Accessed and made backup logs.')
- subprocess.Popen(['start', f'{confPath}//logsFA2.txt'], shell=True)
- shutil.copy(f'{confPath}//logsFA2.txt', f'{confPath}//logsFA2.bkp')
- if len(sys.argv) == 2:
- if sys.argv[1].lower() == 'move':
- move()
- if sys.argv[1].lower() == 'log':
- logOpen()
- elif len(sys.argv) == 3:
- sCode = shelve.open('E://College//config//config')
- if sys.argv[1].lower() == 'ol':
- subprocess.Popen(['start', f'{confPath}//lists//{sCode[str(sys.argv[2])]}.csv'], shell=True)
- elif sys.argv[1].lower() == 'of':
- subprocess.Popen(['start', f'{lbPath}//{sCode[str(sys.argv[2])]}'], shell=True)
- sCode.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement