86 lines
2.5 KiB
Python
86 lines
2.5 KiB
Python
#!python3
|
|
'''
|
|
Created on Oct 5, 20-16
|
|
author: tpweis
|
|
file name: pdf_to_zip.py
|
|
This function finds the .pdf files in a directory (input argument 1)
|
|
and zips them, putting the zipped result in a directory (input argument 2)
|
|
'''
|
|
|
|
import os, time
|
|
import subprocess
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import zipfile
|
|
try:
|
|
import zlib
|
|
compression = zipfile.ZIP_DEFLATED
|
|
except:
|
|
compression = zipfile.ZIP_STORED
|
|
|
|
def main():
|
|
"function main"
|
|
|
|
arglist = sys.argv[1:]
|
|
if(len(arglist)< 1):
|
|
print("Missing PDF Directory argument. Try again")
|
|
sys.exit(3)
|
|
else:
|
|
PDFdir = arglist[0]
|
|
|
|
if(len(arglist) < 2):
|
|
print("Missing ZIP directory argument. Try again")
|
|
sys.exit(4)
|
|
else:
|
|
ZIPdir =arglist[1]
|
|
|
|
# Now ensure that both directorys exist. And, that the the process directory is different
|
|
# from the watch directory
|
|
if not os.path.isdir(PDFdir):
|
|
print("First arg (PDF directory) " + PDFdir + " is not a valid directory")
|
|
sys.exit(5)
|
|
if not os.path.isdir(ZIPdir):
|
|
print("Second arg (ZIP processed directory) " + ZIPdir + " is not a valid directory")
|
|
sys.exit(6)
|
|
|
|
print("ZIPing PDF files from " + PDFdir + ", then placing the result in " + ZIPdir)
|
|
|
|
modes = { zipfile.ZIP_DEFLATED: 'deflated',
|
|
zipfile.ZIP_STORED: 'stored',
|
|
}
|
|
ziplist = dict ([(f, None) for f in os.listdir (PDFdir)])
|
|
if ziplist:
|
|
for f in ziplist:
|
|
try:
|
|
filename, file_extension = os.path.splitext(f)
|
|
except:
|
|
print("Could not get a valid filename")
|
|
sys.exit(1)
|
|
if file_extension == ".pdf":
|
|
normfile = os.path.normpath(PDFdir + "/" + f)
|
|
if not os.path.isfile(normfile):
|
|
print(normfile + " is not a file")
|
|
else:
|
|
outfile = os.path.normpath(ZIPdir + "/" + filename + ".zip")
|
|
print("ZIP this: " + normfile + " to " + outfile)
|
|
zf = zipfile.ZipFile(outfile, mode='w')
|
|
try:
|
|
print("Adding " + f + " with comppression mode ", modes[compression])
|
|
zf.write(normfile, compress_type = compression)
|
|
finally:
|
|
print("closing")
|
|
zf.close()
|
|
else:
|
|
print("No files found in PDF directory")
|
|
|
|
sys.exit(0)
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# execute only if run as a script
|
|
main()
|
|
|
|
|