Duplicated objects' materials are all linked: Problem of bpy.data.objects.copy()?

Hi guys, I am using the following code to duplicate an object and assign materials according to its name.

for filename in dir
    bpy.data.objects['Cube'].copy()
    bpy.context.scene.objects.link(bpy.data.objects['Cube.001'])
    bpy.data.objects['Cube.001'].name = 'Cube'+filename

    #change the material of the newly created object by filename
    bpy.data.objects['Cube'+filename].data.materials[2] = .......

However, every duplicated objects created in this method is having the same material, the last one assigned in the for loop.

Even when I try to change it in the material tab manually, all the objects’s material is changed by this action.

Is there anyway for me to duplicate an object by the method of copy() but at the same time ensure that the materials are not linked so each one has its own material?

object.copy() creates a copy with linked mesh data similar to copy linked operation.
and the material data by default stores in mesh data and can be stored to object data.
so currently you have shared mesh data and shared material among multiple objects.
you can copy mesh data to make it single user by object.data.copy() or you can set the material to be stored in object data by object.material_slots[0].link = ‘OBJECT’

Try changing this by ui and see if it solves the problem
Untitled-1