Skip to content

Save Files and Folder To Drive #446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ More information on contributing and the general code of conduct for discussion
| Rock Paper Scissor 1 | [Rock Paper Scissor 1](https://github.com/DhanushNehru/Python-Scripts/tree/main/Rock%20Paper%20Scissor%201) | A game of Rock Paper Scissors. |
| Rock Paper Scissor 2 | [Rock Paper Scissor 2](https://github.com/DhanushNehru/Python-Scripts/tree/main/Rock%20Paper%20Scissor%202) | A new version game of Rock Paper Scissors. |
| Run Then Notify | [Run Then Notify](https://github.com/DhanushNehru/Python-Scripts/tree/main/Run%20Then%20Notify) | Runs a slow command and emails you when it completes execution. |
| Save File To Drive | [Save File To Drive](https://github.com/DhanushNehru/Python-Scripts/tree/master/Save%20file%20to%20Drive) | Saves all files and folder with proper structure from a folder to drive easily through a python script . |
| Selfie with Python | [Selfie with Python](https://github.com/DhanushNehru/Python-Scripts/tree/main/Selfie%20with%20Python) | Take your selfie with python . |
| Simple DDOS | [Simple DDOS](https://github.com/VanshajR/Python-Scripts/tree/main/Simple%20DDOS) | The code allows you to send multiple HTTP requests concurrently for a specified duration. |
| Simple TCP Chat Server | [Simple TCP Chat Server](https://github.com/DhanushNehru/Python-Scripts/tree/main/TCP%20Chat%20Server) | Creates a local server on your LAN for receiving and sending messages! |
Expand Down
1 change: 1 addition & 0 deletions Save file to Drive/drive/hello.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello World
Empty file.
Empty file.
77 changes: 77 additions & 0 deletions Save file to Drive/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os

# Authenticate
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

# === Prompt for target folder ===
target_folder_name = input("Enter the name of the target folder in Google Drive: ").strip()

def get_or_create_drive_folder(folder_name, parent_id='root'):
"""Get Drive folder ID by name or create it under given parent"""
query = (
f"title='{folder_name}' and "
f"mimeType='application/vnd.google-apps.folder' and "
f"'{parent_id}' in parents and trashed=false"
)
file_list = drive.ListFile({'q': query}).GetList()
if file_list:
print(f"Folder '{folder_name}' found in Google Drive.")
return file_list[0]['id']
else:
print(f"Folder '{folder_name}' not found. Creating it...")
folder_metadata = {
'title': folder_name,
'parents': [{'id': parent_id}],
'mimeType': 'application/vnd.google-apps.folder'
}
folder = drive.CreateFile(folder_metadata)
folder.Upload()
return folder['id']

# === Configuration ===
local_root = r"drive" # Your local folder name
drive_root_id = get_or_create_drive_folder(target_folder_name)

# Folder mapping cache
folder_mapping = {local_root: drive_root_id}

# Recursively walk and upload
for root, dirs, files in os.walk(local_root):
rel_path = os.path.relpath(root, local_root)

if rel_path == '.':
parent_id = drive_root_id
else:
parent_local = os.path.dirname(root)
parent_id = folder_mapping.get(parent_local, drive_root_id)

folder_name = os.path.basename(root)
folder_id = get_or_create_drive_folder(folder_name, parent_id)
folder_mapping[root] = folder_id

for file_name in files:
file_path = os.path.join(root, file_name)

# === Check if file already exists in this Drive folder ===
query = (
f"title='{file_name}' and "
f"'{folder_mapping[root]}' in parents and "
f"trashed=false"
)
existing_files = drive.ListFile({'q': query}).GetList()
if existing_files:
print(f"⏩ File '{file_name}' already exists in '{rel_path}', skipping.")
continue

print(f"⬆️ Uploading '{file_name}' to '{rel_path}'...")
file_drive = drive.CreateFile({
'title': file_name,
'parents': [{'id': folder_mapping[root]}]
})
file_drive.SetContentFile(file_path)
file_drive.Upload()
file_drive = None
69 changes: 69 additions & 0 deletions Save file to Drive/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@


# 📁 Save File and Folder to Drive

A simple utility to interact with Google Drive. This project uses the Google Drive API and requires authentication via `client_secret.json` file.

## 🚀 Features

* Upload files and folders to Google Drive.
* Doesn't change folder structure
* Easy setup for Google Drive API.

---

## 🛠️ Setup Instructions

### 1. Install Dependencies

Make sure you have Python 3 installed.

```bash
pip install -r requirements.txt
```

### 2. Generate `client_secret.json` (Google OAuth Credentials)

To access Google Drive, you’ll need OAuth 2.0 credentials:

1. Go to the **Google Cloud Console**:
👉 [Create OAuth Credentials](https://console.cloud.google.com/apis/credentials)

2. Steps:
* Don't forget to check project name, create new project.
* Search **Google Drive API**, don't get confused with Google Drive Analytics API
* Click Enable
* Go to **Credentials** on left sidebar, click **Create Credential** on top and select **OAuth client ID**
* You might be asked to **configure consent screen**
* Click on it and click Get Started
* Add necessary details like app name and emails, Name example: test123
* Click **Create**
* Now select **Create OAuth Client**
* Choose application type as **Desktop app** and leave name as it is
* Download the JSON file and **rename it to `client_secret.json`**
* Place the file in the project directory
* Now you would have to create test user for using this API.
* Select **Audience** from left Sidebar
* Add all necessary emails under test email and save it

📝 Official Guide:
[Using OAuth 2.0 for Installed Applications](https://developers.google.com/identity/protocols/oauth2)

---

## ▶️ Running the Script

Once everything is set up:

```bash
python main.py
```

---

## 📎 Notes

* Make sure to enable the **Google Drive API** in your Google Cloud Console.

---

Binary file added Save file to Drive/requirements.txt
Binary file not shown.