使用 pydrive 将文件上传到 GoogleDrive 时更改文件名

Changing filename when uploading a file to GoogleDrive by using pydrive

我想在文件名末尾添加时间字符串,我正在使用 pydrive 上传到 Google 驱动器。基本上我尝试在下面编写代码,但我不知道如何适应新的文件变量:

import time
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from time import sleep

gauth = GoogleAuth()           
drive = GoogleDrive(gauth)

timestring = time.strftime("%Y%m%d-%H%M")

upload_file_list = ['Secrets.kdbx']
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': 'folder_id'}]})
    # Read file and set it as the content of this instance.
    upload_file = drive.CreateFile({'title': 'Secrets.kdbx' + timestring, 'mimeType':'application/x-kdbx'}) # here I try to set new filename
    gfile.SetContentFile(upload_file) 
    gfile.Upload() # Upload the file.

获取 TypeError:需要 str、bytes 或 os.PathLike 对象,而不是 GoogleDriveFile

其实我发现了错误。我在 CreateFile() 中更改了文件的名称,并使用字符串切片来保留文件扩展名。当然,此解决方案不能应用于其他不同名称的文件。

upload_file_list = ['Secrets.kdbx']
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'title': [upload_file[:7] + timestring + "." + upload_file[-4:]], # file name is changed here
    'parents': [{'id': '1Ln6ptJ4bTlYoGdxczIgmD-7xcRlJa_7m'}]})
    # Read file and set it as the content of this instance.
    gfile.SetContentFile(upload_file)
    gfile.Upload() # Upload the file. # Output something like: Secrets20211212-1627.kdbx #that's what I wanted :)