Object attribute error when assigning material I am new to blender and having problem with import

I created 4 cubes and exported them into a .obj file.
Then I import the obj file and added texture to one of the cube

import bpy
full_path_to_file = "C:\\Users\\xyz\\Documents\\test.obj"
bpy.ops.import_scene.obj(filepath=full_path_to_file)
object = bpy.data.objects['cube1_Cube_Cube.005']
object.select = True
selectedObject = bpy.context.selected_objects
mat = bpy.data.materials.new('pixelColor')
mat.diffuse_color = (1.0,0.0,1.0)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0
bpy.context.object.data.materials.append(mat)


But this shows error in the last line:


  AttributeError: 'NoneType' object has no attribute 'data'


This error does not occur if I create the object in the file itself(that is if I don't import)
In the example given, you're expecting an active object, (bpy.context.object) when there are none.

Its possible to have selected objects, but nothing active.

In this case you don't even need to have an active object. You can assign the material directly to the object, there is no need to selecting it before:

# create the material
mat = bpy.data.materials.new('MaterialName')
mat.diffuse_color = (1.0,0.0,1.0)
mat.diffuse_shader = 'LAMBERT'
mat.diffuse_intensity = 1.0

# get the object
obj = bpy.data.objects['Cube']

# get the material
mat = bpy.data.materials['MaterialName']

# assign material to object
obj.data.materials.append(mat)

# or overwrite an existing material slot via index operator
obj.data.materials[0] = mat