如何从“按键”列表创建CSV

时间:2018-06-13 18:24:03

标签: python python-2.7 list csv

我尝试从此列表中创建CSV:

[
 ['', '0'], 
 ['user_pos', '1/300'], 
 ['timestamp', '2018-05-13 11:51:28'], 
 ['user_followers', '251'], 
 ['post_link', 'https://www.instagram.com/p/BitpY7rAs-H/?tagged=bio'], 
 ['user_relationship_ratio', '0.66'], ['user_following', '381'], 
 ['tag_info', '  desired amount: 300  |  top postsdisabled: 9  |  
  possible posts: 4514653'], 
 ['Likes', 22],

 ['user', 'frichticook_'], 
 ['post_desc', "Bonjour..."], 
 ['tag_pos', 'Tag1/3'], 
 ['img_url', u'https://scontent-cdg2']
]

其中'user_pos''timestamp'等是列的标题?

提前谢谢

我已经尝试过了:

def WriteListToCSV(csv_file,csv_columns,data_list):
  try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.writer(csvfile, dialect='excel', 
        quoting=csv.QUOTE_NONNUMERIC)
        writer.writerow(csv_columns)
        for data in data_list:
            writer.writerow(data)
  except IOError as (errno, strerror):
        print("I/O error({0}): {1}".format(errno, strerror))    
  return 

但它给我这样的东西:

enter image description here

1 个答案:

答案 0 :(得分:4)

您应该转置列表(交换行和列):

with open(csv_file, 'w') as csvfile:
    writer = csv.writer(csvfile, dialect='excel', 
                        quoting=csv.QUOTE_NONNUMERIC)
    for data in zip(*data_list): # Where the magic happens
        writer.writerow(data)