简体   繁体   中英

Determine if folder or file using Dropbox Python API

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM