Search code examples
pythonpython-3.xpydrive

Changing filename when uploading a file to GoogleDrive by using pydrive


I want to add time string to the end of filenames which I am uploading to Google Drive by using pydrive. Basically I try to code below, but I have no idea how to adapt new file variable:

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.

getting TypeError: expected str, bytes or os.PathLike object, not GoogleDriveFile


Solution

  • Actually I found the mistake. I changed name of the file inside CreateFile() and used string slicing to keep the file extension. Of course, this solution cannot be applied to other files with different names.

    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 :)