How can I add UV coords to a mesh from script? I am adapting an old script to Blender 2.6, the script reads mesh data from a custom file type and then creates a mesh array with that data.

I managed to make almost all of it, but U can't set the UV values of each vertex to the mesh.

I create the mesh array like this:

for i in range(0,numeroparts):
    malla.append(bpy.data.meshes.new(name="2k_Part"+str(i)))
    uv = []
    xyz= []
    for j in range(0,numerovertxpart[i]):
        line=file.readline()
        x,y,z,u,v=float(line.split()[0].replace(',','.')),float(line.split()[1].replace(',','.')),float(line.split()[2].replace(',','.')),float(line.split()[3].replace(',','.')),float(line.split()[4].replace(',','.'))
        uv.append((u,v))
        xyz.append((x,y,z))
        print(x,y,z)


    aa = []
bb = []
cc = []
faces= []               

for j in range(0,numerofacexpart[i]):
    line=file.readline()
    a,b,c=int(line.split()[0]),int(line.split()[1]),int(line.split()[2])
    faces.append((a,b,c))
    aa.append(a)
    bb.append(b)
    cc.append(c)
    print(a,b,c)

malla[i].from_pydata(xyz, [], faces)





for q in range(len(malla[i].polygons)):
    #malla[i].faces[q].mode |= Blender.Mesh.FaceModes['TWOSIDE']
    #malla[i].faces[q].transp = Blender.NMesh.FaceTranspModes['ALPHA']
    #malla[i].faces[q].uv=Mathutils.Vector(uv[aa[q]]), Mathutils.Vector(uv[bb[q]]), Mathutils.Vector(uv[cc[q]])


My problem is here, the lines commented out are how it worked in Blender 2.49:

for q in range(len(malla[i].polygons)):
        #malla[i].faces[q].mode |= Blender.Mesh.FaceModes['TWOSIDE']
        #malla[i].faces[q].transp = Blender.NMesh.FaceTranspModes['ALPHA']
        #malla[i].faces[q].uv=Mathutils.Vector(uv[aa[q]]), Mathutils.Vector(uv[bb[q]]), Mathutils.Vector(uv[cc[q]])
Below you find a very well-performaning solution to set mesh UVs from a source in a per-vertex format to Blender's per-loop (face corner).

This assumes you have a sequence of float pairs (UV coord),
e.g. ((0.2, 0.1), (0.8, 0.9), (0.2,0.1), ...).

import bpy
from random import random

me = bpy.context.object.data

# Sample data
vert_uvs = [(random(), random()) for i in range(len(me.vertices))]

me.uv_textures.new("test")
me.uv_layers[-1].data.foreach_set("uv", [uv for pair in [vert_uvs[l.vertex_index] for l in me.loops] for uv in pair])


Original thread: Importing UV coordinates