Skip to main content


Got an interesting question from a developer:





I need to rename a file in Box using the Python SDK API. I know the filename, but I guess to rename it I need a file object. How do I create a file object when all I have is the name of the file? The file is located in the root folder.

Consider this python script:



from boxsdk import JWTAuth, Client



class CFG:

"""config class"""

JWT_CONFIG_FILE = ".jwt.config.json"

AS_USER = "18622116055"

PARENT_FOLDER_ID = "165803865043" # folder id 0 is root folder





def get_box_client(as_user: bool = False):

"""get a box client"""

auth = JWTAuth.from_settings_file(CFG.JWT_CONFIG_FILE)

service_client = Client(auth)

if not as_user:

return service_client

user = service_client.user(CFG.AS_USER)

return service_client.as_user(user)





def print_items(items):

"""print items"""

print("\n")

print("Type\tID\tName")

print("----\t--\t----")

for item in items:

print(f"{item.type}\t{item.id}\t{item.name}\t")





def main():

"""main function"""



client = get_box_client(as_user=True)



# print current user info

user = client.user().get()

print(f"Current User: {user.name}\tid:{user.id}")



# list files in root folder

items = client.folder(CFG.PARENT_FOLDER_ID).get_items()

print_items(items)



In the above example we have a box app, configured with JWT authentication. We are grabbing a client for which the service user of the app is impersonating the as-user who actually has access to the content we want to locate.



I’m also using another parent folder, but you can replace this with 0 which always represent the user root folder.



This initial part, outputs the items inside the parent folder, this test checks if we actually have access to the file.



In my case the output is:



Type    ID      Name

---- -- ----

file 974207525964 Audio.mp3

...

file 974229112148 Single Page.docx

file 974225001875 ZIP.zip



So let’s locate file audio.mp3 in this parent folder using the search:



    # get parent folder

parent_folder = client.folder(CFG.PARENT_FOLDER_ID).get()



# search for audio.mp3 text string

file_name_exact_match = '"audio.mp3"' # note the double quotes

ancestor_folders = (parent_folder,)

result_type = ("file",) # what type of result we are looking for

content_types = ("name",) # look only in file name for query string



items = client.search().query(

file_name_exact_match,

ancestor_folders=ancestor_folders,

result_type=result_type,

content_types=content_types,

)

print_items(items)



And the output is:



Type    ID      Name

---- -- ----

file 974207525964 Audio.mp3



And now we just rename the file:



# get the first item of type file (there shoul dbe only 1 or none)

item = next((item for item in items if item.type == "file"), None)



# rename the file

if item is not None:

item.update_info(data={"name": "Audio_renamed.mp3"})



And we can see the file renamed:



# list files in parent folder

items = client.folder(CFG.PARENT_FOLDER_ID).get_items()

print_items(items)



Type ID Name

---- -- ----

file 974207525964 Audio_renamed.mp3

...

file 974229112148 Single Page.docx

file 974225001875 ZIP.zip



Please note that the search engine does not index the file immediately, a new file takes a few minutes to show up on the search.



If you know the parent folder, you can implement a manual name match using the items() method on the folder.



# list files in parent folder

items = client.folder(CFG.PARENT_FOLDER_ID).get_items()



item = next((item for item in items if item.name == "ZIP.zip"), None)

if item is not None:

item.update_info(data={"name": "ZIP_renamed.zip"})



# list items in parent folder

items = client.folder(CFG.PARENT_FOLDER_ID).get_items()

print_items(items)



Resulting in:



Type    ID      Name

---- -- ----

file 974207525964 Audio_renamed.mp3

...

file 974225084827 Preview SDK Sample Excel.xlsx

file 974229112148 Single Page.docx

file 974225001875 ZIP_renamed.zip


Reply