I have code that zips all files inside a directory but ignores subfolders. I would like to include subfolders and their files recurvisely.
I have tried changing the for from "for f in files" to "for f in dirs" but I ended up zipping empty folders and not the files.
Any ideas how I can achieve this?
# Creates the zip on the current directory for the given folder and moves them to a target directory
# Input parameter "directory": The directory that contains the files to be zipped
# Input parameter "age": Only zip files older than this age.
# Input parameter "targetdir": Move zip file created into the target directory
# Return: Zipfilename: The zip file that was created
# Return: Count: Number of files zipped or zero if no files were zipped
def makeZipMove(directory, age, targetdir):
os.chdir(directory)
now = datetime.now()
milis = str(datetime.now())[24:]
fileprefix = now.strftime("Archive_%Y%m%d_%H%M%S_"+milis)
zipfilename = fileprefix + '.zip'
delta = time.time() - (float(age) * 86400)
UniversalZipfile = zipfile.ZipFile(zipfilename, "w", zipfile.ZIP_DEFLATED)
count = 0
for root,dirs,files in os.walk(directory):
for f in files:
try:
if os.stat(f).st_mtime < delta :
if not f.endswith(parser.get('defaults', 'default_dont_consider_for_zipping')):
UniversalZipfile.write(f)
os.remove(f)
logging.info("Zipping: " + f)
count = count+1
except PermissionError as ex:
logging.warning(ex);
logging.warning("This will not prevent the zipping. Please clear or ignore this file")
except:
logging.error("Unexpected error occured")
logging.fatal(traceback.format_exc())
break
if count!=0:
if not f.endswith(parser.get('defaults', 'default_dont_consider_for_zipping')):
UniversalZipfile.close()
shutil.move(zipfilename, targetdir)
# Remove the zipfile again if it has zero files.
if count == 0:
UniversalZipfile.close()
os.remove(zipfilename)
return zipfilename, count ```