Python Learning: Automate Boring Stuff with Python | Chapter 8 : My Solution to Project: Backing Up a Folder into a Zip File

Just my solution to the project

I found the solution to the project provided in the book really good, but it zipped the entire folder structure in the absolute path. Something I am not pleased with. By adding the filepath base name to the zipfile.Zipfile.write() function, after the absolute filepath (of the file to be written),  I was able to prevent that unecessary folder zipping.

 

Suggestions are welcomed! 

 



#Backs up given file in a zip file and numbers accordingly
#Usage: python backupzip <filepath>

import sys, os, re, zipfile


#TODO: get filepath
if len(  sys.argv ) == 2:
	filepath = sys.argv[1]
	filepath = os.path.abspath(filepath)
#TODO: check if file path is valid
	if os.path.exists(filepath):
		#TODO: get list of files in the current directory
		backupNum = 1
		filepath_name = os.path.basename(filepath)
		filepath_name = filepath_name.split(".")
		print(filepath_name)
		regex_pattern = "^{}_\d+.zip$".format(filepath_name[0])
		regExp = re.compile(regex_pattern)
		for filename in os.listdir():
		#TODO: get number of files with filename
			match = regExp.match(filename)
			if match:
				backupNum+=1
		#TODO: create zipfile and zip filepath 
		name = filepath_name[0] + "_" + str(backupNum) + ".zip"
		textZip = zipfile.ZipFile(name, "w")
		#TODO: walk through entire folder tree 
		for folderName,subfolders, files in os.walk(filepath):
			print("Adding files from {}".format( folderName ))
			#textZip.write(folderName)
			for file in files:
				filp = os.path.join(folderName, file)
				textZip.write(filp, os.path.basename(filp),   compress_type=zipfile.ZIP_DEFLATED)
		textZip.close()
	else:
		print("given file path does not exists")

else:
	print("Usage: python backupzip <filepath>")