box / box-python-sdk

Box SDK for Python
http://opensource.box.com/box-python-sdk/
Apache License 2.0
418 stars 215 forks source link

Get File ID from navigating the path? #704

Closed M62ChainSlapLover closed 2 years ago

M62ChainSlapLover commented 2 years ago

I currently have a python script that skims through the Local Box Directory on my windows machine and spits out the file path for a particular file based on type. I've poked around the API and the developer forums and haven't seen a method to gather the file id from the path. I need this file id so I can concatenate it into a clickable link in an excel file.

lukaszsocha2 commented 2 years ago

Hi @Nasco540, unfortunately API doesn't support getting file id by its path. Here you have code snippet you can use to achieve this. Unfortunately you have to iterate through items in folder to find an item by its name.

from boxsdk.client import Client
from boxsdk.object.folder import Folder

def get_item_id_by_name_in_folder(folder: Folder, item_name: str):
    for item in folder.get_items():
        if item.name == item_name:
            return item.id
    raise Exception(f"No item found with name {item_name}")

def get_id_by_path(client: Client, path: str):
    split = path.split('/')
    subfolders = split[:-1]
    file_name = split[-1]

    current_dir = client.root_folder()
    for item_name in subfolders:
        item_id = get_item_id_by_name_in_folder(current_dir, item_name)
        current_dir = client.folder(item_id)

    return get_item_id_by_name_in_folder(current_dir, file_name)

if __name__ == "__main__":
    # authenticate client

    path = 'folder/sub-folder/another-sub-folder/file.pdf'
    print(get_id_by_path(client, path))

Hope this solves your issue. If not let us know. @lukaszsocha2