簡體   English   中英

Python 3-將Google電子表格另存為csv

[英]Python 3 - Saving a google spreadsheet as a csv

我正在嘗試將私有的Google電子表格保存到csv中。 我找到了另一個解決此問題的線程( 使用Python從Google Docs下載電子表格 ),但是答案可以追溯到2012年。我曾嘗試使用一種解決方案,但遇到了錯誤。 這是我目前正在使用的代碼

import csv
import gspread

// used the actual username, password and doc-id in the python script
username = "username"
password = "password"
docid = "doc-id"

client = gspread.login(username, password)
spreadsheet = client.open_by_key(docid)

for i, worksheet in enumerate(spreadsheet.worksheets()):
    filename = docid + '-worksheet' + str(i) + '.csv'
    with open(filename, 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(worksheet.get_all_values())

這是IDLE拋出的錯誤

writer.writerows(worksheet.get_all_values())
TypeError: 'str' does not support the buffer interface

正如您必須認識到的那樣,我對python來說是相當新的東西,並且我正在嘗試解決這個問題。 誰能指出我使用的代碼有什么問題?

在Python 3中,以文本模式打開文件,並將newline設置為''以讓CSV編寫器控制要寫入的換行符:

with open(filename, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(worksheet.get_all_values())

(2016年7月)現在訪問Google表格文件時,GData的使用已過時。 當前將Google表格導出為CSV的現代方法是使用Google Drive API。 我用Python 2 + 3代碼示例撰寫了一篇博文 ,向您展示了如何執行此操作。 還要檢查另一個線程,在該線程中我添加了比2012年更現代的答案。通過該更新,該線程應標記為該另一個線程的重復。 要從更一般的意義上從Python訪問Google表格,請查看對一個相關問題的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM