skip to Main Content

I am trying to rename a file in Azure File Share using the Azure python SDK. But the problem I’m facing is, it removes the file instead of renaming it.

with directory_client.get_file_client(file_name=project_from_db.project_name) as rename_client:
    rename_client.rename_file(new_name=new_data['project_name'])

Is anything wrong here?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it with the same code below, by just adding the path of the old file with the new name of the file, to the new_path parameter .

    new_file_path = <file-path> + new_data['project_name']
    with directory_client.get_file_client(file_name=project_from_db.project_name) as rename_client:
        rename_client.rename_file(new_name = new_file_path)
    

    By doing the above change, the file will be renamed in the same path as the old file was.

    Hope it helps other people out there facing the same issue!


  2. I tried in my environment and got the below results:

    Initially, In my environment, I have the file name with sprite.html in Azure File share.

    Portal:
    enter image description here

    You can use the below code to rename a file in Azure File Share using Azure Python SDK.

    Code:

    from azure.storage.fileshare import ShareServiceClient
    
    
    # Define the connection string and file share name
    connection_string = "your-connection string"
    file_share_name = "fileshare2"    
            
    file_name="sprite.html"
    new_file_name="sprite326.html"
    
    share_service_client = ShareServiceClient.from_connection_string(connection_string)
    share_client = share_service_client.get_share_client(file_share_name)
    file_client = share_client.get_file_client(file_name)
    
    new_file_client=share_client.get_file_client(new_file_name) 
    new_file_client.start_copy_from_url(file_client.url)
    
    file_client.delete_file()
    print("The file is Renamed successfully:",{new_file_name})
    

    Output:

    The file is Renamed successfully: {'sprite326.html'}
    

    enter image description here

    Portal:
    enter image description here

    Reference:

    Azure Storage File Share client library for Python | Microsoft Learn

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search