Advertisement
Guest User

File Arranger

a guest
Jan 26th, 2020
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.14 KB | None | 0 0
  1. #! python3
  2.  
  3. import os
  4. import re
  5. import shelve
  6. import csv
  7. import datetime
  8. import shutil
  9. import logging
  10. import sys
  11. import subprocess
  12.  
  13. m = datetime.datetime.today()
  14. mo = str(m.month)
  15. colPath = 'E://College'
  16. confPath = 'E://College//config'
  17. lbPath = 'E://College//University of the Philippines Los Baños'
  18. os.chdir(colPath)
  19. logging.basicConfig(filename=f'{confPath}//logsFA2.txt', level=logging.DEBUG,
  20. format='%(asctime)s - %(levelname)s - %(message)s',
  21. datefmt='%Y-%m-%d %H:%M:%S')
  22. fileReg = re.compile(r'''(
  23. ^([a-zA-Z0-9]*) #Classcode
  24. ([.]) #seperator
  25. ([. a-zA-Z0-9,]*) #Name of the File
  26. (\.docx | \.xlsx | \.pptx | \.pub | \.jpeg | \.png | \.jpg | \.psd | \.\w+)$ #File Extension
  27. )''', re.VERBOSE | re.IGNORECASE | re.DOTALL)
  28. listFile = os.listdir(colPath)
  29. listMatch = 0
  30.  
  31.  
  32. def checker():
  33. global listMatch
  34. sCode = shelve.open('E://College//config//config')
  35. for i in listFile:
  36. for groups in fileReg.findall(i):
  37. if groups[1] in sCode:
  38. listMatch += 1
  39. sCode.close()
  40. if listMatch is not 0:
  41. return True
  42. else:
  43. return False
  44.  
  45.  
  46. def writer(code, fid, name,path):
  47. global m
  48. with open(f'{confPath}//lists//{code}.csv', 'a', newline='') as csvfile:
  49. filewriter = csv.writer(csvfile, delimiter=',')
  50. date = m.strftime("%d-%m-%Y %H:%M:%S")
  51. filewriter.writerow([fid,f"{name}", f"{path}", date])
  52.  
  53.  
  54. def csvCounter(code):
  55. lineCount = 0
  56. if os.path.exists(f'{confPath}//lists//{code}.csv') is True:
  57. with open(f'{confPath}//lists//{code}.csv') as csvfile:
  58. lineCount = (len(list(csvfile)))
  59. elif os.path.exists(f'{confPath}//lists//{code}.csv') is not True:
  60. with open(f'{confPath}//lists//{code}.csv', 'wb') as csvfile:
  61. filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
  62. return lineCount
  63.  
  64. def dirChecker(folder, ext):
  65. sCode = shelve.open('E://College//config//config')
  66. if os.path.exists(f"{lbPath}//{folder}//{sCode['months'][mo]}//{ext}") is not True:
  67. path = f"{lbPath}//{folder}//{sCode['months'][mo]}//{ext}"
  68. os.makedirs(path)
  69. sCode.close()
  70.  
  71. def move():
  72. fMoved = 0
  73. sCode = shelve.open('E://College//config//config')
  74. if checker() is True:
  75. logging.info('Initiated moving session.')
  76. for y in listFile:
  77. for groups in fileReg.findall(y):
  78. if groups[1] in sCode:
  79. fileNum = csvCounter(sCode[groups[1]]) + 1
  80. newFileName = f'{groups[3]}{groups[4]}'
  81. if groups[4] in sCode:
  82. dirChecker(f'{sCode[groups[1]]}', f'{sCode[groups[4]]}')
  83. newFilePath = f"{lbPath}//{sCode[groups[1]]}//{sCode['months'][mo]}//{sCode[groups[4]]}//{newFileName}"
  84. try:
  85. shutil.move(groups[0], newFilePath)
  86. except PermissionError:
  87. logging.warning(f'Skipped {groups[0]} due to opened file.')
  88. else:
  89. writer(sCode[groups[1]], fileNum, f'{newFileName}', f'{newFilePath}')
  90. logging.info(f'[{groups[1]}]Filename {groups[0]} was moved, ID {fileNum}.')
  91. fMoved += 1
  92. elif groups[4] not in sCode:
  93. newFilePath = f"{lbPath}//{sCode[groups[1]]}//{sCode['months'][mo]}//{newFileName}"
  94. try:
  95. shutil.move(groups[0], newFilePath)
  96. except PermissionError:
  97. logging.warning(f'Skipped {groups[0]} due to opened file.')
  98. else:
  99. writer(sCode[groups[1]], fileNum, newFileName, newFilePath)
  100. logging.info(f'[{sCode[groups[1]]}]Filename {groups[0]} was moved, ID {fileNum}.')
  101. fMoved += 1
  102.  
  103. if fMoved is not 0:
  104. logging.info(f'A total of {fMoved} was moved.')
  105. elif fMoved is 0:
  106. logging.info(f'No unopened files were moved')
  107. else:
  108. logging.warning('No file matched the subject codes.')
  109. sCode.close()
  110.  
  111.  
  112. def logOpen():
  113. logging.info(f'Accessed and made backup logs.')
  114. subprocess.Popen(['start', f'{confPath}//logsFA2.txt'], shell=True)
  115. shutil.copy(f'{confPath}//logsFA2.txt', f'{confPath}//logsFA2.bkp')
  116.  
  117.  
  118. if len(sys.argv) == 2:
  119. if sys.argv[1].lower() == 'move':
  120. move()
  121. if sys.argv[1].lower() == 'log':
  122. logOpen()
  123.  
  124.  
  125. elif len(sys.argv) == 3:
  126. sCode = shelve.open('E://College//config//config')
  127. if sys.argv[1].lower() == 'ol':
  128. subprocess.Popen(['start', f'{confPath}//lists//{sCode[str(sys.argv[2])]}.csv'], shell=True)
  129. elif sys.argv[1].lower() == 'of':
  130. subprocess.Popen(['start', f'{lbPath}//{sCode[str(sys.argv[2])]}'], shell=True)
  131. sCode.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement