Search code examples
pythondjangoazureazure-file-share

How to rename a file in Azure File Share using Azure Python SDK?


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?


Solution

  • 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