【问题标题】:Changing filename when uploading a file to GoogleDrive by using pydrive使用 pydrive 将文件上传到 GoogleDrive 时更改文件名
【发布时间】:2021-12-12 15:14:16
【问题描述】:

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

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、字节或 os.PathLike 对象,而不是 GoogleDriveFile

【问题讨论】:

    标签: python python-3.x pydrive


    【解决方案1】:

    其实我发现了错误。我在 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 :)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多