Home > Back-end >  Python: How to replace old uploaded files to Google Drive
Python: How to replace old uploaded files to Google Drive

Time:06-03

I have this script written in python which looks thrue folder 'CSVtoGD', list every CSV there and send those CSV's as independent sheets to my google drive. I am trying to write a line which will delete the old files when I run the program again. What am I missing here? I am trying to achieve that by using:

sh = gc.del_spreadsheet(filename.split(".")[0] " TTF")

Unfortunately the script is doing the same thing after adding this line. It is uploading new files but not deleting old ones.

Whole script looks like that

import gspread
import os
gc = gspread.oauth(credentials_filename='/users/user/credentials.json')

os.chdir('/users/user/CSVtoGD')

files = os.listdir()

for filename in files:
   if filename.split(".")[1] == "csv":
      folder_id = '19vrbvaeDqWcxFGwPV82APWYTmB'
      sh = gc.del_spreadsheet(filename.split(".")[0] " TTF")
      sh = gc.create(filename.split(".")[0] " TTF", folder_id)
      content = open(filename, 'r').read().encode('utf-8') 
      gc.import_csv(sh.id, content)



Everything is working fine, CSVs from folder are uploaded to google drive, my problem is with deleting the old CSV (with the same name as new ones)

CodePudding user response:

When I saw the document of gspread, it seems that the argument of the method of del_spreadsheet is the file ID. Ref When I saw your script, you are using the filename as the argument. I thought that this might be the reason for your issue. When this is reflected in your script, it becomes as follows.

From:

sh = gc.del_spreadsheet(filename.split(".")[0] " TTF")

To:

sh = gc.del_spreadsheet(gc.open(filename.split(".")[0]   " TTF").id)

Note:

  • When the Spreadsheet of the filename of filename.split(".")[0] " TTF" is not existing, an error occurs. Please be careful about this.

Reference:

Added:

From your reply of When I try do delete other file using this method from My Drive it is working well., it was found that my proposed modification can be used for "My Drive". But, it seems that this cannot be used for the shared drive.

When I saw the script of gspread again, I noticed that the current request cannot search the files in the shared drive using the filename. And also, I confirmed that in the current gspread, the Spreadsheet ID cannot be retrieved using gspread. Because the files cannot be searched from all shared drives. By this, I would like to propose the following modified script.

Modified script:

import gspread
import os
from googleapiclient.discovery import build

gc = gspread.oauth(credentials_filename='/users/user/credentials.json')

service = build("drive", "v3", credentials=gc.auth)


def getSpreadsheetId(filename):
    q = f"name='{filename}' and mimeType='application/vnd.google-apps.spreadsheet' and trashed=false" # or 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.")
        exit()
    return items[0]["id"]


os.chdir('/users/user/CSVtoGD')

files = os.listdir()

for filename in files:
    fname = filename.split(".")
    if fname[1] == "csv":
        folder_id = '19vrbvaeDqWcxFGwPV82APWYTmB'
        oldSpreadsheetId = getSpreadsheetId(fname[0]   " TTF")
        sh = gc.del_spreadsheet(oldSpreadsheetId)
        sh = gc.create(fname[0]   " TTF", folder_id)
        content = open(filename, "r").read().encode("utf-8")
        gc.import_csv(sh.id, content)
  • In this modification, in order to retrieve the Spreadsheet ID from the filename in the shared drive, googleapis for python is used. Ref

  • But, in this case, it supposes that you have the permission for writing to the shared drive. Please be careful about this.

  • Related