Make You Own Backup Program with Python in Less than 10 Lines.

Dhruv Padhiyar
2 min readDec 18, 2020

Hello Everyone, Let’s write a program that can take a backup of your entire system using Python.

In this, we haven’t used any special module just built-in modules from Python. Let’s start with importing all modules.

from os import walk
from os.path import getsize
from time import perf_counter
from zipfile import ZipFile
from datetime import date

Ok now, let us start with searching all the files in a path.

def search():
'''
Search All Non-Hidden Files
'''
PATH = '/home/pi'
all_files = []
start = perf_counter()
print('Scanning For File System...Please Wait')
for root, dirs, files in walk(PATH):
if '.' not in root:
for y in files:
if not y.startswith('.'):
complete_path = root+'/'+y
all_files.append(complete_path)
print(f"Total Time Taken To Scan all files: {round(perf_counter()-start, 2)} seconds")
return all_files

We declared the path for all the files we want to search in the PATH variable. Then will start the counter to count the time taken for scanning all the files in the path mentioned above. Now we start with the for-loop:- walk() which will scan all the files in the given path. Now since this will scan for all files including hidden files too. But I don’t need that right now, so I wrote a simple if-function that ignores all the hidden files for now. I have also created an empty List that will have a full path of non-hidden files and will store it in that list. Finally, we will end the function by returning the all_files list and the time it took to scan all files.

Now, will write a small function that will take a backup of all the files mentioned in the list.

def createArchive(all_files):
'''
Create Archive with Date as Name
'''
zip_filename = str(date.today())+'.zip'
print('Starting Backup....It might take some time')
with ZipFile(zip_filename,'w') as z:
for x in all_files:
z.write(x)
print('The Backup File is ' + zip_filename)
print('The Size of Backup is '+ str(round(getsize(zip_filename)/(1024*1024),2))+ 'MB')
print('Ending... the Program')

Here I have used the date as the filename for the backup. Momentarily will zip up every file in the list with the built-in ZipFile Function. We also display the size of the zip using the getsize function.

Our Main Function will be similar….

if __name__ == "__main__":
all_files = search()
createArchive(all_files)

Woah, We made our backup system from scratch with python. Now You are ready to upload it to Google Drive. The entire code is available on my GitHub with some additional functions. Do check it out.

Have A Delightful Day!!!

--

--