简体   繁体   English

更新 Google Drive 上的 CSV 文件,以便在带有 PyDrive 的 Data Studio 上使用

[英]Update CSV file on Google Drive to be used on Data Studio with PyDrive

I need to update a CSV file located on my Drive because I use it on a dashboard in Google Data Studio.我需要更新位于我的 Drive 上的 CSV 文件,因为我在 Google Data Studio 的仪表板上使用它。 Until now, I was using this code:到目前为止,我一直在使用以下代码:

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()

On which:其中:

  • "previous_GDS_df" is the content of the CSV file I'm updating, “previous_GDS_df”是我正在更新的 CSV 文件的内容,
  • ""path_to_GDS_file" the path to my local CSV file, on which I do the modifications, ""path_to_GDS_file" 本地 CSV 文件的路径,我在该文件上进行修改,
  • "df_GDS" the df of my modifications, the elements I'd like to append to my file on Drive. “df_GDS”是我修改的df,我想把append的元素放到我Drive上的文件中。

Basically, my theory was the following: "I extract the previous content of the file, I append to it the new content then I edit my Drive file with 'SetContentFile' and I upload it all."基本上,我的理论如下:“我提取文件的先前内容,我将 append 放入新内容,然后我使用 'SetContentFile' 编辑我的 Drive 文件并将其全部上传。”

The problem is that when I edit my file on Drive, I need to reconnect everytime my file in my dashboard GDS because I think that SetContentFile erase entirely the previous file Drive to write a new one.问题是,当我在 Drive 上编辑文件时,每次我在仪表板 GDS 中的文件时都需要重新连接,因为我认为 SetContentFile 会完全擦除以前的文件 Drive 以写入新文件。 In this case, I must reconnect the Drive file to GDS because it was deleted and rewrited.在这种情况下,我必须将 Drive 文件重新连接到 GDS,因为它已被删除和重写。

So, I'm looking for a solution to update my Drive file so I will not have to reconnect everytime my file to the dahsboard and the modifications will appear magically.因此,我正在寻找一种解决方案来更新我的云端硬盘文件,这样我就不必每次将我的文件重新连接到仪表板并且修改会神奇地出现。

Do you have a solution?你有解决方案吗? My theory is surely bad.我的理论肯定是坏的。 I'm missing something somewhere.我在某处遗漏了一些东西。

Thank you for your help, ask me if more information is needed.感谢您的帮助,请问我是否需要更多信息。

I don't know much about pydrive , but in order to update a file via Drive API, you have to use Files: update .我对pydrive了解不多,但是为了通过 Drive API 更新文件,您必须使用Files: update This allows you either to just update file metadata, or also file content.这使您可以仅更新文件元数据,也可以更新文件内容。

Here's a possible sample that uses the official Python library :这是使用官方 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()

Note:笔记:

You'll first have to download your credentials file, as explained in the quickstart referenced below.您首先必须下载您的凭据文件,如下面引用的快速入门中所述。

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 PyDrive 替换/更新 Google Drive 上的文件? - How to replace/update a file on Google Drive with PyDrive? 使用PyDrive将大文件上传到Google云端硬盘 - Upload a huge file to Google Drive using PyDrive Pydrive 从 Google Drive 删除文件 - Pydrive deleting file from Google Drive 有什么方法可以使用 pydrive 在 Google 驱动器中读取多种不同的文件类型,例如 xlsv、csv、xls? - Is there any way that i can read multiple different file type like xlsv, csv, xls in Google drive using pydrive? 谷歌驱动器的pydrive库未使用请求以请求的格式下载文件 - pydrive library for google drive is not downloading file in requested format using requests 使用PyDrive将Pandas DataFrame作为Excel文件直接上传到Google云端硬盘 - Upload a Pandas DataFrame as Excel file directly to Google Drive using PyDrive 无法使用 PyDrive 在谷歌驱动器中的文件夹之间移动文件 - Cannot move a file across folders in google drive using PyDrive 使用PyDrive将文件上传到Google-Drive Teamdrive文件夹 - Upload File to Google-drive Teamdrive folder with PyDrive PyDrive Google Drive自动认证 - Pydrive google drive automate authentication 无法通过 pydrive 进行身份验证到谷歌驱动器 - Fail to authenticate with pydrive to google drive
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM