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: