I have this part of script which is listing files in my local folder, replaces old files in Google Drive by files from local folder and adds new files to Google Drive from local folder.
How to modify the script to check if there is file which is about to get added to GD because I have a kernel crash error in situation when: there is no file "A.csv" in GD, the script is uploading file "A.csv" - just after that I got kernel crash because the script is trying to get spreadsheetID of file which is not present in Google Drive yet. GetsppreadsheetID is defined in other part of script not mentioned here. Thank you for your help. I have no idea how to make additional "IF" to avoid getting spreadsheetID of file which has not been yet in Google Drive.
import gspread
import os
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
gc = gspread.oauth(credentials_filename='/users/krzysztofpaszta/credentials.json')
service = build("drive", "v3", credentials=gc.auth)
folder_id = '19vrbvaeDqWcxFGwPV82APWYTmBMEn-hi'
def getSpreadsheetId(filename, filePath):
q = "name='" + filename + "' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false"
res = service.files().list(q=q, fields="files(id)", corpora="allDrives", includeItemsFromAllDrives=True, supportsAllDrives=True).execute()
items = res.get("files", [])
if not items:
print("No files found.")
file_metadata = {
"name": filename,
"parents": [folder_id],
"mimeType": "application/vnd.google-apps.spreadsheet",
}
media = MediaFileUpload(filePath + "/" + filename + ".csv")
file = service.files().create(body=file_metadata, media_body=media, fields="id", supportsAllDrives=True).execute()
id = file.get("id")
print("File was uploaded. The file ID is " + id)
exit()
return items[0]["id"]
filePath = '/users/krzysztofpaszta/CSVtoGD'
os.chdir(filePath)
files = os.listdir()
for filename in files:
fname = filename.split(".")
if fname[1] == "csv":
oldSpreadsheetId = getSpreadsheetId(fname[0], filePath) - THIS PART NEEDS TO BE CHANGED
sh = gc.del_spreadsheet(oldSpreadsheetId)
sh = gc.create(fname[0], folder_id)
content = open(filename, "r").read().encode("utf-8")
gc.import_csv(sh.id, content)