by shigemk2

当面は技術的なことしか書かない

gspreadでごにょごにょしよう

gspreadでgoogle driveのスプレッドシートを1行ずつ読み込みつつ、
UnicodeWriterのやつで1行ずつ書き出している。

# -*- coding: utf-8 -*-
# http://docs.python.org/2/library/csv.html
import csv, codecs, cStringIO
class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

# http://burnash.github.io/gspread/
import os
import sys
import csv
sys.path.append(os.getcwd())

# パスワードとかのデータはこっちから持ってくる
from config_data import *

data_file_name = '{0:s}_data'.format(sys.argv[1])
print os.path.split(PROJECT_DIR)[-1]
print CSV_DATA[os.path.split(PROJECT_DIR)[-1]]
print data_file_name
import gspread

client = gspread.login(MAIL_ADDRESS, PASSWORD)
sheet_data = CSV_DATA[os.path.split(PROJECT_DIR)[-1]][data_file_name]

spreadsheet = client.open_by_key(sheet_data['key'])
ws = None
for worksheet in spreadsheet.worksheets():
    if worksheet.title == sheet_data['title']:
        ws = worksheet
        break

if ws is None:
    print 'Not Exist:'
    print sheet_data
    sys.exit()
print PROJECT_DIR
writer = UnicodeWriter(file(os.path.join(PROJECT_DIR, 'ローカルのレポジトリでcsvファイルを突っ込んでるディレクトリ名', data_file_name + '.csv'), 'w'), lineterminator='\n')
writer.writerows(worksheet.get_all_values()[1:])

config_data.py

# -*- coding: utf-8 -*-
MAIL_ADDRESS = 'メールアドレス'
PASSWORD = 'パスワード'

CSV_DATA = dict(
    プロジェクト名 = dict(
        シートの名前1  = dict(key="キー", title=u"シートの名前1",),
        シートの名前2  = dict(key="キー", title=u"シートの名前2",),
        シートの名前3  = dict(key="キー", title=u"シートの名前3",),
        ),
    )

PROJECT_DIR = 'プロジェクトのフルパス'