用服务器批量生成的文件是HTML,每次同步到本地查看尊嘟好麻烦,所以想了个办法直接一键上传谷歌云,然后到本地Drive客户端文件夹里直接打开就行了。
步骤如下,可供诸君参考~
pip install pydrive
import os from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive def get_folder_id(drive, parent_id, folder_name): # List folders in the parent folder file_list = drive.ListFile( { 'q': f"'{parent_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList() for file in file_list: if file['title'] == folder_name: return file['id'] # Folder not found, create it folder_metadata = { 'title': folder_name, 'mimeType': 'application/vnd.google-apps.folder', 'parents': [{'id': parent_id}] } folder = drive.CreateFile(folder_metadata) folder.Upload() return folder['id'] def upload_file_to_google_drive(local_path, drive_path, client_secrets_path): # Authenticate and initialize PyDrive gauth = GoogleAuth() gauth.LoadClientConfigFile(client_secrets_path) gauth.CommandLineAuth() # Use command-line authentication drive = GoogleDrive(gauth) # Split the drive path into components path_parts = drive_path.strip('/').split('/') # Set up folder structure parent_id = 'root' # Start from the root folder for part in path_parts[:-1]: # Go through each part of the path except the last one parent_id = get_folder_id(drive, parent_id, part) # Upload file file_title = path_parts[-1] # The last part of the path is the file title file_to_upload = drive.CreateFile({'title': file_title, 'parents': [{'id': parent_id}]}) file_to_upload.SetContentFile(local_path) file_to_upload.Upload() print(f'File uploaded successfully to {drive_path}') def upload_folder_to_google_drive(local_folder, drive_path, client_secrets_path): # Authenticate and initialize PyDrive gauth = GoogleAuth() gauth.LoadClientConfigFile(client_secrets_path) gauth.CommandLineAuth() # Use command-line authentication drive = GoogleDrive(gauth) # Split the drive path into components path_parts = drive_path.strip('/').split('/') # Set up folder structure parent_id = 'root' # Start from the root folder for part in path_parts: # Go through each part of the path parent_id = get_folder_id(drive, parent_id, part) # Iterate over all files in the local folder for root, _, files in os.walk(local_folder): for file_name in files: file_path = os.path.join(root, file_name) file_to_upload = drive.CreateFile({'title': file_name, 'parents': [{'id': parent_id}]}) file_to_upload.SetContentFile(file_path) file_to_upload.Upload() print(f'File {file_name} uploaded successfully to {drive_path}') if __name__ == "__main__": client_secrets_path = '.../client_secrets.json' # Replace with the correct path local_path = '.../result' # Local Path drive_path = '.../test/' # Desired path on Google Drive upload_folder_to_google_drive(local_path, drive_path, client_secrets_path)