You just need to change line 22 of the original script to material.name = os.path.basename(link_node.image.filepath)
. (It's now line 21 in the script below.)
Also, cleaned up the script a bit so the bpy.context.object.active_material_index
doesn't get messed up. There is no need to touch it because you already have the material in the for material in ...
loop.
import bpy
import os
# get the selected object
obj = bpy.context.active_object
# Go through list of materials assigned to selected object
for material in obj.data.materials:
old_name = material.name
try:
# Get the nodes in the node tree
nodes = material.node_tree.nodes
# Get a principled node
principled = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
# Get the slot for 'base color'
base_color = principled.inputs['Base Color'] #Or principled.inputs[0]
# Get the link
link = base_color.links[0]
link_node = link.from_node
# Rename the material to the image file's name including the extension
material.name = os.path.basename(link_node.image.filepath)
# Print the results
print( "Material Old Name:", old_name, )
print( "Material New Name:", material.name )
print( )
except BaseException as err:
print(f'Skipping material "{old_name}", no Image Texture connected to the Principled BSDF found.')