Joh*_*est 2 python google-sheets google-sheets-api
我有一个 CSV 文件,我想将其放入 Google Sheet 中的 Sheet3 中。我希望有人可以帮助我完成这段代码。我正在使用谷歌API。到目前为止,我已经将 csv 上传到谷歌驱动器。现在我想更改代码以更新sheet3中的特定google工作表而不是创建新工作表。您将在下面找到我用来创建包含 CSV 数据的新工作表的代码。
# Import Csv to Google Drive
import os
import glob
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
# line used to change the directory
os.chdir(r'DIRECTORY OF CSV')
list_of_files = glob.glob('DIRECTORY OF CSV\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
upload_file_list = [latest_file]
for upload_file in upload_file_list:
gfile = drive.CreateFile({'parents': [{'id': 'THE GOOGLE ID'}]})
# Read file and set it as the content of this instance.
gfile.SetContentFile(upload_file)
gfile.Upload() # Upload the file.
Run Code Online (Sandbox Code Playgroud)
我相信您的目标如下。
在这种情况下,下面的示例脚本怎么样?
当使用googleapis for python时,下面的示例脚本怎么样?
service = build("sheets", "v4", credentials=creds) # Please use your script for authorization.
spreadsheet_id = "###" # Please put your Spreadsheet ID.
sheet_name = "Sheet3" # Please put the sheet ID of the sheet you want to use.
csv_file = "###" # Please put the file path of the CSV file you want to use.
f = open(csv_file, "r")
values = [r for r in csv.reader(f)]
request = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=sheet_name, valueInputOption="USER_ENTERED", body={"values": values}).execute()
Run Code Online (Sandbox Code Playgroud)
当使用gspread for python时,下面的示例脚本怎么样?
import gspread
import csv
client = gspread.oauth(###) # Please use your script for authorization.
spreadsheet_id = "###" # Please put your Spreadsheet ID.
sheet_name = "Sheet3" # Please put the sheet ID of the sheet you want to use.
csv_file = "###" # Please put the file path of the CSV file you want to use.
spreadsheet = client.open_by_key(spreadsheet_id)
worksheet = spreadsheet.worksheet(sheet_name)
f = open(csv_file, "r")
values = [r for r in csv.reader(f)]
worksheet.update(values)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4366 次 |
| 最近记录: |