Writing to file script failed
It seems that you mixed two methods. You can either use :

file_object = open('myfilename','w')
file_object.write(ob.name)
file_object.close()


or

with open('myfilename','w') as file_object:
    file_object.write(ob.name)
    #no need to close


The second option is better (see https://www.pythonforbeginners.com/files/with-statement-in-python).

Both options only require you to import bpy