Skip to content

Instantly share code, notes, and snippets.

@Antyos
Last active April 28, 2020 21:01
Show Gist options
  • Save Antyos/21e3d9a542385bc006470b7b176872e5 to your computer and use it in GitHub Desktop.
Save Antyos/21e3d9a542385bc006470b7b176872e5 to your computer and use it in GitHub Desktop.
Creo Compression
# Python 3.8
# Licensed with MIT License
DESCRIPTION = """
Creo Compression Program v1.0.1
Written by Andrew Glick on 4/12/2020
Appends old Creo version files in a folder to a zip file with the same name as the folder
Deletes files after adding them to the zip
If no folder specified, defaults to current working directory (in command line)
Creo version files end in '.###'. Examples include:
part.prt.1
assembly.asm.3
Usage:
python CreoCompression.py [options] "/path/to/folder/1" "/path/to/folder/2" ...
Options:
-h Display this text
-r Recursive directory search
"""
import sys
from typing import List
from os import path
import os
import zipfile
# Zip file compression format
# Can use: ZIP_STORED, ZIP_DEFLATED, and ZIP_BZIP2, ZIP_LZMA. See: https://docs.python.org/3/library/zipfile.html
compressionMethod = zipfile.ZIP_DEFLATED
# Helper funciton to print a list
def unpack(s: List) -> str:
return ', '.join(map(str, s))
# Get list of files to zip
def getFilesToZip(dirPath: str = './', debug: bool = False) -> List[str]:
files = os.listdir(dirPath) # All files in directory
if debug:
print(f'All files: {{{unpack(files)}}}') # Print all files
# Get only Creo files (end in `.###` i.e. ends in number)
creoFiles = [ file for file in files if (file.rpartition('.')[2].isdigit()) ]
if debug:
print(f'Creo files: {{{unpack(creoFiles)}}}') # Print Creo files
# Find last version of all files. Items on list are unique
fName: str = ''
lastFName: str = ''
uniqueFiles: List[str] = []
# Populate uniqueFiles
for file in creoFiles:
part = file.rpartition('.')
# Newly encountered file
if (fName := part[0]) != lastFName:
uniqueFiles.append(file)
lastFName = fName
# Repeat of a file, check if more updated version
# Assumes if a repeated file, it's a repeat of the most recent item in uniqueFiles
elif int(part[2]) > int(uniqueFiles[-1].rpartition('.')[2]):
uniqueFiles.pop()
uniqueFiles.append(file)
if debug:
print(f'Unique files: {{{unpack(uniqueFiles)}}}')
# Get files that will be zipped are creoFiles - uniqueFiles
filesToZip = [ file for file in creoFiles if file not in uniqueFiles ]
if debug:
print(f'Files to zip: {{{unpack(filesToZip)}}}')
return filesToZip
# Zip files
def zipFiles(filesToZip: List[str], dirPath: str, zipName: str = 'archive.zip', deleteFiles: bool = False) -> bool:
# print(f'Zip name: {zipName}') # Print zip name
try:
# Open zip file
fullZipName = path.join(dirPath, zipName) # Get full zip name
zf = zipfile.ZipFile(fullZipName, mode='a') # Open Zip file
# Add files to zip
for file in filesToZip:
# Full path of file
filePath = path.join(dirPath, file)
# Add file to the zip file
# first parameter file to zip, second filename in zip
zf.write(filePath, file, compress_type=compressionMethod)
# Close the file
zf.close()
# Delete files after closing the zip file (for safety)
if deleteFiles:
for file in filesToZip:
# Full path of file
filePath = path.join(dirPath, file)
# Delete files
os.remove(filePath)
return True # All good
except PermissionError:
print('Unable to open file. Make sure it is not already open')
except FileNotFoundError as e:
print(f'File not found: {e}')
# Failed
return False
# Main
def main():
# Paths list
paths: List[str] = []
# Get command line options and arguments
opts = [opt for opt in sys.argv[1:] if opt.startswith('-')]
args = [arg for arg in sys.argv[1:] if not arg.startswith('-')]
# If no args specified, set to the current working directory
if len(args) == 0:
args = [os.getcwd()]
# Check for options
# Help menu
if '-h' in opts:
print(DESCRIPTION)
return
# Recursive directory search
elif '-r' in opts:
for rootdir in args:
for folder, subfolder, files in os.walk(rootdir):
paths.append(folder)
# Normal
else:
# Append args to path
paths.extend(args)
# For each path in args array
for dirPath in paths:
print() # Blank line for spacing
print(f'Path: {dirPath}') # Print path name
dirName = path.basename(dirPath) # Get name of folder
filesToZip: List[str] = getFilesToZip(dirPath=dirPath, debug=False) # Get files to zip
# If there are files to zip
if len(filesToZip) > 0:
zipName = f'{dirName}-Archive.zip' # Zip file name
ok = zipFiles(filesToZip, dirPath, zipName, deleteFiles=True) # Zip files
if ok:
print(f'Added {len(filesToZip)} files: {{{unpack(filesToZip)}}} to archive: {zipName}')
# No files to zip
else:
print('No old versions found')
print('\nFinished!\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment