pythonboxsdk

Replace existing file on upload


I am trying to upload a file in to a folder in the box using the below code:

folder_id = '22222'
new_file = client.folder(folder_id).upload('/home/me/document.pdf')
print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))

This code is not replacing the existing document.pdf in the box folder, rather it is keeping the older version of the file. I would like to remove the file in the target and keep the latest file. How to achieve this?


Solution

  • Since your goal is to replace the original file, you can try to overwrite its existing content. Here is an example. You will need to check for the filename if it is already present in the BOX folder though

    folder_id = '22222'
    file_path = '/home/me/document.pdf'
    
    results = client.search().query(query='document', limit=1, ancestor_folder_ids=[folder_id], type='file', file_extensions=['pdf'])    
    file_id = None
    for item in results:
        file_id = item.id
    
    if file_id:
        updated_file = client.file(file_id).update_contents(file_path)
        print('File "{0}" has been updated'.format(updated_file.name))
    else:
        new_file = client.folder(folder_id).upload(file_path)
        print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))