简体   繁体   中英

GoogleAPI, Python: How to avoid getting ID of specified file in Google Drive

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)

Okay first off i am not a python expert but I can see the issue. In the sction of code below. You create the new file. which returns to you a file id.

id = file.get("id")

Yet you are still returning

return items[0]["id"]

which is empty.

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"]

May i suggest something like this where if you do insert the file then you return the id to your code. while if the file exists you are returning the id from the response.

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)
    return id
else:
    return items[0]["id"]

If this doesn't work let me know i will boot up Pycharm and give it a shot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM