Determine if folder or file using Dropbox Python API

Question:

I am trying to use the Dropbox API v2 to get a list of all folders and all files, and view the metadata associated with each.

I have been able to make it list all files and folders in my Dropbox root, and return the metadata, however I can’t figure out how to determine if the output metadata is for a file FileMetadata or folder FolderMetadata.

When I print the returned values from my query it shows them as File or Folder

import dropbox 

def print_metadata(dbfile):
    md = dbx.files_get_metadata(dbfile)
    print (md)

dbx = dropbox.Dropbox('MYAPIKEY')

myfiles = ['/someotherfile.jpg', '/Camera Uploads']

for myfile in myfiles:
    print_metadata(myfile)

File:

FileMetadata(name='someotherfile.jpg', id='id:1234567890', client_modified=datetime.datetime(2013, 1, 15, 20, 51, 3), server_modified=datetime.datetime(2017, 8, 24, 21, 32, 52), rev='1234567890', size=162012, path_lower='/someotherfile.jpg', path_display='/someotherfile.jpg', parent_shared_folder_id=None, media_info=None, sharing_info=None, property_groups=None, has_explicit_shared_members=None, content_hash='1234567890')

Folder:

FolderMetadata(name='Camera Uploads', id='id:0987654321', path_lower='/camera uploads', path_display='/Camera Uploads', parent_shared_folder_id=None, shared_folder_id=None, sharing_info=None, property_groups=None)

However as I can’t determine which is which from within python, I can’t print specific metadata values such as the file size

print(md.size)

AttributeError: 'FolderMetadata' object has no attribute 'size'

What do I need to do to check if the returned object is File or Folder, or specify to only return folders or only return files in my lists? That way I should be able to loop through all folders and files throughout my entire dropbox.

Asked By: Midavalo

||

Answers:

You can use isinstance to check the type of the object, which can be FileMetadata, FolderMetadata, or DeletedMetadata. There’s an example here:

https://github.com/dropbox/dropbox-sdk-python/blob/master/example/updown.py#L91

Answered By: Greg

You can use this function/line if you don’t want to read through the accepted answers code:

def isFile(dropboxMeta):
    return isinstance(dropboxMeta,dropbox.files.FileMetadata)
Answered By: jman

I find this to be more useful for downstream folder creation.

def get_file_exists(dbx,db_file):
    try:
        md = dbx.files_get_metadata(db_file)
        exists_bool = True
        return exists_bool
    except Exception as error_response:
        exists_bool = False
        return exists_bool

dropbox_exists_boolean = get_file_exists(dbx,'/{}'.format(filename))
if dropbox_exists_boolean == False:
    # create dropbox folder
    res = dbx.files_create_folder_v2('/{}'.format(filename))