python excel csv帮助。怎么做格式化

时间:2013-07-02 19:46:35

标签: python excel csv

我有问题。如果我用文字解释,我会搞砸,所以这里是图片。

我的代码:

import csv

def mytest():
    s1 = 'post'
    s2 = 'a_num'
    s3 = ['personA','GenderA','personB','GenderB','personC','GenderC','personD','GenderD','personE','GenderE',]
    s4 = ['comment by F','comm_F_gender','comment','ano_num','comment by G','comm_G_gender','comment','ano_num','comment by H','comm_H_gender','comment','ano_num']      
    with open('mytestfb.csv', 'a') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow([s1.encode('utf-8'),s2.encode('utf-8')])
        x = 0
        while(x < len(s3)):
            spamwriter.writerow(['','',s3[x].encode('utf-8'),s3[x+1].encode('utf-8')])
            x += 2
        x = 0
        while(x < len(s4)):
            spamwriter.writerow(['','','','',s4[x].encode('utf-8'),s4[x+1].encode('utf-8'),s4[x+2].encode('utf-8'),s4[x+3].encode('utf-8')])
            x += 4

这是这段代码的作用:

enter image description here

这就是我需要代码的地方:

enter image description here

1 个答案:

答案 0 :(得分:1)

那不可能是整个代码吗?因此,如果我理解s4中的每四个项目,s3中的两个项目代表一行。

def mytest():
    s1 = 'thing1'
    s2 = 'a_number'
    s3 = ['personA','GenderA','personB','GenderB','personC','GenderC','personD','GenderD','personE','GenderE',]
    s4 = ['comment by F','comm_F_gender','comment','ano_num','comment by G','comm_G_gender','comment','ano_num','comment by H','comm_H_gender','comment','ano_num']      
    with open('mytestfb.csv', 'a') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        exportlist=[s1,s2]
        for count in range(len(s3)/2):
            exportlist+=s3[count*2-1:count*2]
            try:
                exportlist+=s4[count*4-1+count*4]
            except IndexError:
                pass
        spamwriter.writerow(exportlist.encode('utf-8'))