'Import csv file from local to google sheet using python

Currently I'm exploring the google API and I have script that currently works as importer of my CSV file to google sheet, but I have issue since my script is creating new sheet once I import csv, my plan is to modify it and make it not create new sheet but to import and update the spreadsheet.


import gspread
from datetime import date
from oauth2client.service_account import ServiceAccountCredentials


scope = [
    "https://spreadsheets.google.com/feeds",
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive",
]
credentials = ServiceAccountCredentials.from_json_keyfile_name("pdkey123.json", scope)
client = gspread.authorize(credentials)


today = date.today()
now_date = today.strftime("%m/%d/%y")
spreadsheet = client.open("CSVImport")
worksheet = spreadsheet.add_worksheet(title=now_date, rows="1000", cols="5")
now_sheet = now_date + '!' + 'A1'

def ImportCsv(csvFile, sheet, cell):

    if "!" in cell:
        (tabName, cell) = cell.split("!")
        wks = sheet.worksheet(tabName)
    else:
        wks = sheet.sheet1
    (firstRow, firstColumn) = gspread.utils.a1_to_rowcol(cell)

    with open(csvFile, "r") as f:
        csvContents = f.read()
    body = {
        "requests": [
            {
                "pasteData": {
                    "coordinate": {
                        "sheetId": wks.id,
                        "rowIndex": firstRow - 1,
                        "columnIndex": firstColumn - 1,
                    },
                    "data": csvContents,
                    "type": "PASTE_NORMAL",
                    "delimiter": ",",
                }
            }
        ]
    }
    return sheet.batch_update(body)


ImportCsv("test_file.csv", spreadsheet, now_sheet)

Can someone help me to modify my script? TYIA



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source