列出不同行上的索引csv文件

时间:2014-04-03 21:30:45

标签: python csv indexing

写入csv时是否可以将列表中的每个索引拆分为新行?

例如,我将一些索引附加到列表中,当我写入csv时,它们都打印在同一行上。

当我写入csv文件时,来自route.append的当前输出是......

("Index1")("Index2")("Index3")("Index4")("Index5")("Index6")

我想把它写成:

("Index1")
("Index2")
("Index3")
("Index4")
("Index5")
("Index6")

我知道我可以写

rec=index[1]
f.writerow(rec)

并重复6次..问题是,我的列表中可以有2个索引到100个索引,所以我需要做的是能够根据列表中的索引量打印n个索引

感谢。
    F =开放(" route1.csv"" W&#34)     f.truncate()     f.close()

print "Route Calculator"
cur = (0, 0)
route = [0]
xy = [ ]
z= ()
zz= []
dest=[]
n = input("Enter number of destinations to visit:")
a = range(1, n + 1)
cidd = []
for i in range(n):
    cid=raw_input("Enter Customer ID")
    f3=csv.reader(open("data/customer.csv",'r'))
    for row in f3:
        if row[0]==cid:
            street=row[2]
            pcode=row[3]
            tel=row[4]
            x=eval(row[5])
            y=eval(row[6])
            z=row[1]
            xy.append((x,y))
            zz.append(((cid,z)))
            cidd.append((((cid,z,street,pcode,tel))))

print "Destinations:",cidd
dest = [ ]
ndd =[ ]
for i in range(n):
    nd = []
    for i in xy:
        i = list(i)
        distance = round(math.hypot((cur[0] - i[0]), (cur[1] - i[1])),4)
        nd.append(distance)

    print "Current location:", cur
    print "Coordinates to travel to:", xy
    print "Distances to destinations:", nd, "minimum distance:", min(nd)
    nn = (xy[nd.index(min(nd))][0], xy[nd.index(min(nd))][1])
    print "Nearest neighbour:", nn
    print "Nearest destination:", cidd[xy.index(nn)]
    print
    dest.append(((min(nd))))
    ndd=sum(dest)
    route.append(((cidd[xy.index(nn)],(min(nd)))))
    del cidd[xy.index(nn)]
    xy.remove(nn)
    cur = list(nn)

distance = round(math.hypot(nn[0], nn[1]), 4)
dest.append(distance)
route.append(0)
cidd.extend(dest)
print "Destination List:",route
o=open("route1.csv",'ab')
f=csv.writer(o)
rec3=("Driver:",driver)
f.writerow(rec3)
rec4=("Date:",(time.strftime("%d/%m/%Y")))
f.writerow(rec4)
header=(["CID..","Customer Name..........","Address.........","Postcode..","Telephone..","Distance from prev"])
f.writerow(header)
rec=(route)
f.writerow(rec)
rectotal=("Total Distance to Travel",ndd)
f.writerow(rectotal)
print "Route Saved to route1.csv"

这是我当前的代码及其route.append我试图索引到单独的行。感谢

2 个答案:

答案 0 :(得分:0)

假设以下工作

rec=(route[1],)
f.writerow(rec)

您可以使用for循环来避免多次写入。

for i in xrange(len(index)):
    rec=(route[i],) 
    f.writerow(rec)

答案 1 :(得分:0)

只需使用writerows功能。

示例:

f.writerows(["a","b","c"])

将输出

a
b
c