0

I have a script to copy csv files to google drive but I want if an existing filename in the drive exists, when I run the script again, it should replace the existing filename.

Currently, a duplicate file is created i.e duplicate test.csv.

Below is the code

    # create drive api client
    service = build('drive', 'v3', credentials=credentials)

    file_metadata = {'name': 'test.csv','parents':[destination_folder_id]}
    media = MediaFileUpload(
      source_file_path,
      mimetype='file/csv')
    
    file = service.files().create(
      body=file_metadata,
      media_body=media,
      fields='id').execute()
    print(f'File ID: {file.get("id")}')
Shadow Walker
  • 979
  • 5
  • 27
  • 51
  • Have you reviewed the option to gather a list of files and based on that generated by using .list and from there create a conditional before running the creation? Mainly because the .create would just generate a brand new ID for the file no matter the name https://stackoverflow.com/questions/56857760/list-of-files-in-a-google-drive-folder-with-python#:~:text=Use%20the%20special%20command%20%27!%27,of%20folder%20drive%20you%20specify. – Ricardo Jose Velasquez Cruz Nov 10 '22 at 23:33

1 Answers1

2

In Google Drive, the files are managed by the unique ID instead of the filename. By this, the files with the same filename can be created in the same folder. I think that this is the reason for your issue. So, in this case, first, it is required to check whether the files with the same filename are existing in the folder. When this is reflected in your script, how about the following modification?

Modified script:

destination_folder_id = "###" # Please set folder ID.
source_file_path = "###" # Please set source_file_path
filename = "test.csv" # This is from your script.

service = build("drive", "v3", credentials=credentials)
results = service.files().list(pageSize=1,fields="files(id)",q="'" + destination_folder_id + "' in parents and trashed=false and name='" + filename + "'").execute()
files = results.get("files", [])
media = MediaFileUpload(source_file_path, mimetype="file/csv")
if files != []:
    print(files)
    file_metadata = {}
    file = service.files().update(fileId=files[0]["id"], body=file_metadata, media_body=media, fields="id").execute()
    print(f'File ID: {file.get("id")}')
else:
    file_metadata = {"name": filename, "parents": [destination_folder_id]}
    file = service.files().create(body=file_metadata, media_body=media, fields="id").execute()
    print(f'File ID: {file.get("id")}')
  • In this modification, first, it confirms whether the file of the filename is existing in the folder. And, when the file is found, the file is overwritten by the file. When the file is not found, a new file is created with the filename.

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165