[英]How to overwrite CSV Files using Google Drive API with Python?
I want to create a simple script that will upload multiple CSV to my Drive every day.我想创建一个简单的脚本,每天将多个 CSV 上传到我的驱动器。 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.这样做的问题是,每次我运行我的程序时,都会创建一个新的 CSV 文件而不是替换它。
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?此代码将我的桌面文件夹中的所有 CSV 文件成功创建到 Google Drive 位置,但是我怎样才能使它覆盖以前创建的文件而不是每次都创建新版本?
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如果要更新现有文件,则要使用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.您需要做的是执行 file.list 以检查具有该名称和 mimetype 的文件是否已存在,如果存在,则使用其 fileId 您可以更新该文件。
If you dont know how to search for a file check the q parameter for file.list.如果您不知道如何搜索文件,请检查 file.list 的 q 参数。 it will let you search for a file by name, mimetype and directory.它可以让您按名称、mimetype 和目录搜索文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.