Skip to content

Instantly share code, notes, and snippets.

@spookyahell
Created January 1, 2019 16:01
Show Gist options
  • Save spookyahell/dcab8767fd04869fbaf20cbf66714579 to your computer and use it in GitHub Desktop.
Save spookyahell/dcab8767fd04869fbaf20cbf66714579 to your computer and use it in GitHub Desktop.
What better way to backup Python files (and related docs) then by a simple python script?
from os import listdir, sep
from os.path import isfile, isdir, join
import zipfile
import time
from sys import stdout
zip_filename = time.strftime('pythonBackup-%Y%m%d-%H%M%S.zip')
zf = zipfile.ZipFile(zip_filename,'w')
archive_these = {r'C:\Users\XYZ\Desktop\Python':'PythonFilesOnDesktop'}
archive_types = ['.py','.txt','.sh','.log','.session','.json','.ini','.svg']
ALLFILES = {}
def handlefile(filename, parent, main_dir):
archive_it = False
for at in archive_types:
if filename.endswith(at):
archive_it = True
if archive_it:
file_name = join(parent, filename)
file_name_archive = join(archive_these[main_dir.strip(sep)], file_name.replace(main_dir,''))
ALLFILES[file_name] = file_name_archive
def handledir(dirname, parent, main_dir):
dir_base = join(parent, dirname)
dir_itms = listdir(dir_base)
for item in dir_itms:
if isfile(join(dir_base, item)):
handlefile(item, dir_base, main_dir)
else:
if isdir(join(dir_base, item)):
handledir(item, dir_base, main_dir)
for main_dir in archive_these:
if not main_dir.endswith(sep):
main_dir += sep
root = listdir(main_dir)
for item in root:
if isfile(item):
handlefile(item, main_dir, main_dir)
else:
if isdir(item):
handledir(item, main_dir, main_dir)
#~ ALLFILES.sort()
for idx, file in enumerate(ALLFILES):
zf.write(file, ALLFILES[file])
stdout.write(f'\rWritten file {idx+1}/{len(ALLFILES)}... ')
print('\nBackup complete')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment