![]() |
|
[Tut] Automate Backup to Google Drive with Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Automate Backup to Google Drive with Python (/thread-100468.html) |
[Tut] Automate Backup to Google Drive with Python - xSicKxBot - 12-25-2022 Automate Backup to Google Drive with Python 4.5/5 – (2 votes) Project Description Every day I find myself in a position where I have to take daily backup of a certain folder named Reports and store it in my Google drive. This is an essential folder for me since I store all the necessary documents (especially reports). Hence, keeping a backup of this folder in the cloud gives me a cushion in case of any fault in my local system. However, this involves a long and repetitive manual process wherein I have to sign in to my google account, navigate to the folder where I store my backup files and then copy and paste new files to this folder. This consumes some time, and I was thinking of automating the entire process. That is when I came up with a wonderful automation script that not only saved me all the hassle of manually backing up my files but also ensured that I could do so without the help of any fancy third-party software application. So, this is what my script does –
Thus, in this article, I will guide you through implementing the same automated backup technique to store files from your local system to Google drive on a daily basis using Python. So, without further delay, let’s discover the power of Python automation through our project. [b]Step 1: Setting up Google Drive API[/b] Before you start writing your script, it is essential to ensure that you have set up your Google Drive API properly. Simply put, the Drive API allows you to interact with Google Drive storage and supports several popular programming languages, such as Java, JavaScript, and Python.
![]()
![]()
![]()
![]()
![]() You are done with the first step. Now we need the Credentials that will authorise us when we talk to the Google Drive API from our script.
![]()
![]()
![]() The final step is to enable the Google Drive API so that you can communicate with it using the credentials from your script.
![]() That’s it! You are now all set to communicate with the Google Drive API using your script to connect and store files in your Google Drive. [b]Step 2: Create the Automation Script [/b] Now that everything is ready, we are now ready to write a program to generate daily backups on the cloud. To contact the API, you will need the help of the Code: PyDriveCode: pip3 install PyDriveAfter installing the Code: PyDrive
Code: from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
import os
Code: gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None: gauth.LocalWebserverAuth()
elif gauth.access_token_expired: gauth.Refresh()
else: gauth.Authorize()
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)Note that even after you have set up the Code: pydriveCode: secret_client.jsonCode: LoadCredentialsFileCode: SaveCredentialsFile
Code: def upload_file_to_drive(): for x in os.listdir(path): file_list = drive.ListFile( {'q': "'16jhq7j-SWZmKF_vU0MmKNX' in parents and trashed = False"}).GetList() try: for file1 in file_list: if file1['title'] == os.path.join(path, x): file1.Delete() except: passExplanation: The key value pair Code: 'q': "'16jhq7j-SWZmKF_vU0MmKNX'![]() Simply copy it and paste it in your script. A major problem here is whenever you copy the files and store them in your Google drive folder, the pre-existing files also get copied and duplicate files cover up the space unnecessarily. Thus, instead of simply copying the files blindly, you can opt to replace them instead. So, you can follow a two-step process – (i) Delete the pre-existing files (ii) Store a fresh copy of all the files in the folder. That is exactly what has been done in the above script. [b]Putting it all Together[/b]
Code: from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
import os gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None: gauth.LocalWebserverAuth()
elif gauth.access_token_expired: gauth.Refresh()
else: gauth.Authorize()
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
path = r"C:\reports"
def upload_file_to_drive(): for x in os.listdir(path): file_list = drive.ListFile( {'q': "'16jhq7j-SWZmKF_vUehGalNf6Yr0MmKNX' in parents and trashed = False"}).GetList() try: for file1 in file_list: if file1['title'] == os.path.join(path, x): file1.Delete() except: pass f = drive.CreateFile({'parents': [{'id': '16jhq7j-SWZmKF_vUehGalNf6Yr0MmKNX'}]}) f.SetContentFile(os.path.join(path, x)) f.Upload() f = None upload_file_to_drive()Output: ![]() Schedule Regular Backup One final task that needs to be taken care of is ensuring that the backup script runs at a particular time every day. There are different ways of doing this. You can use the Code: scheduleCode: scheduleHence, I would suggest using the windows task scheduler. Windows Task Scheduler is built-in windows program that facilitates you with the ability to schedule and automate tasks in Windows by running scripts or programs automatically at a given moment.
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Once, you have set this up, your trigger is now active and your Python script will run automatically every day. Summary Hurrah! You have successfully set up your automated backup script to take the necessary backups on a scheduled time every day without the need to do anything manually. I hope the complete walkthrough of the project helped you! Subscribe and stay tuned for more interesting projects in the future. |