[英]Update CSV file on Google Drive to be used on Data Studio with PyDrive
我需要更新位於我的 Drive 上的 CSV 文件,因為我在 Google Data Studio 的儀表板上使用它。 到目前為止,我一直在使用以下代碼:
previous_GDS_df = pd.read_excel(path_to_GDS_file)
pd.concat(objs=[previous_GDS_df, df_GDS]).to_excel(path_to_GDS_file, index=False)
f = drive.CreateFile({'id': spreadsheet_id})
f.SetContentFile(path_to_GDS_file)
f.Upload()
其中:
基本上,我的理論如下:“我提取文件的先前內容,我將 append 放入新內容,然后我使用 'SetContentFile' 編輯我的 Drive 文件並將其全部上傳。”
問題是,當我在 Drive 上編輯文件時,每次我在儀表板 GDS 中的文件時都需要重新連接,因為我認為 SetContentFile 會完全擦除以前的文件 Drive 以寫入新文件。 在這種情況下,我必須將 Drive 文件重新連接到 GDS,因為它已被刪除和重寫。
因此,我正在尋找一種解決方案來更新我的雲端硬盤文件,這樣我就不必每次將我的文件重新連接到儀表板並且修改會神奇地出現。
你有解決方案嗎? 我的理論肯定是壞的。 我在某處遺漏了一些東西。
感謝您的幫助,請問我是否需要更多信息。
我對pydrive
了解不多,但是為了通過 Drive API 更新文件,您必須使用Files: update 。 這使您可以僅更新文件元數據,也可以更新文件內容。
這是使用官方 Python 庫的可能示例:
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from apiclient.http import MediaFileUpload
SCOPES = ['https://www.googleapis.com/auth/drive'] # If modifying these scopes, delete the file token.json.
fileId = "DRIVE_FILE_ID" # Change to yours
filePath = "LOCAL_FILE_PATH" # Change to yours
def getCreds(): # Authentication
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def updateFile(service, fileId): # Call the API
media = MediaFileUpload(filePath, mimetype='text/csv', resumable=True)
res = service.files().update(fileId=fileId,media_body=media,fields="*").execute()
return res
def main():
creds = getCreds()
service = build('drive', 'v3', credentials=creds)
updateFile(service, fileId)
if __name__ == '__main__':
main()
您首先必須下載您的憑據文件,如下面引用的快速入門中所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.