2013-07-02 38 views
1

我有一个问题。如果我用文字解释,我会搞砸的,所以这里是在图片中。python excel csv help。如何格式化

我的代码:

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

+4

您的代码和发布一样,都没有。 –

+0

@MartijnPieters哎呀!错误的代码大声笑。它现在已被编辑,使其匹配 – user1681664

回答

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')) 
+0

不,它不是整个代码,但它是我遇到的问题。简而言之,我从网上提取信息并将其放入Excel中。我把它解压成这种格式。 – user1681664

+0

对不起:这是你的原帖。基本上,当您使用'writerow'时,它会创建一个新行,我不相信您可以在不关闭文件并再次阅读的情况下添加该行。或者做我的建议。希望它有帮助 – JonLeslieHarding

+0

对不起也意识到,你会得到一个索引错误,所以我修复它,以复制我认为你要去的东西。对不起,如果我是offbase – JonLeslieHarding