I want to create a simple script that will upload multiple CSV to my Drive every day. Currently here is my script. The problem with this is that every time I run my program, a new CSV file will be created instead of replaced.
CLIENT_SECRET_FILE ='Client_secret_QSCtest.json'
API_NAME = 'drive'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/drive']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
def export_csv_file(file_path: str, parents: list=None):
if not os.path.exists(file_path):
print(f'{file_path} not found.')
return
try:
file_metadata = {
'name' : os.path.basename(file_path).replace('.csv',''),
'mimeType' : 'application/vnd.google-apps.spreadsheet',
'parents' : parents
}
media = MediaFileUpload(filename=file_path, mimetype='text/csv')
response = service.files().create(
media_body=media,
body=file_metadata
).execute()
print(response)
return response
except Exception as e:
print(e)
return
csv_files = os.listdir('./')
for csv_files in csv_files:
export_csv_file(os.path.join('', csv_files))
export_csv_file(os.path.join('', csv_files), parents=['1apjzSu8fugs6EvGwJVof3MDGlhZXoT_G'])
This code creates all the CSV files in my desktop folder successfully to the Google Drive location, but how can I make it so that it overwrites the previously created file instead of creating new versions every time?
Thank you!
You are running a file. create
response = service.files().create(
media_body=media,
body=file_metadata
).execute()
If you want to update an existing file then you want to use File.update
response = service.files().update(
fileId=file_id,
body=file_metadata ,
media_body=media).execute()
What you will need to do is to do a file.list to check if the file with that name and mimetype already exists if it does then using its fileId you can update that file.
If you dont know how to search for a file check the q parameter for file.list. it will let you search for a file by name, mimetype and directory.
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.