如何在python中将列表写入csv文件的特定列

时间:2017-02-01 05:47:22

标签: python csv

我有一个嵌套列表,每个嵌套列表都有多个字符串:

[['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com],['http:/house.com/09','http:/google.com/076','http://rather.com']...]

我的目标是在第一列中获取每个列表的第一个元素,并在第二列和第三列中获取其余元素

想要在csv文件中得到结果:

col1                 col2                  co3            col4
http:/house.com/06   http:/google.com/09   http:6000.com
http:/house.com/04   http:/google.com/03   http:600.com    http://900.com
http:/house.com/09   http:/google.com/076  http://rather.com

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:0)

分隔符不应在标题行和数据行中更改。由于您在几行中有一个空字符串,因此应该使用逗号分隔符。试试吧:

使用pandas

import pandas as pd

l1 = [['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com'],['http:/house.com/09','http:/google.com/076','http://rather.com']]

df = pd.DataFrame(data=l1, columns=['col1','col2','col3','col4']).fillna('')
df.to_csv('file1.csv', index=None)

这是数据框的样子:

enter image description here

使用csv包:

import csv

l1 = [['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com'],['http:/house.com/09','http:/google.com/076','http://rather.com']]
with open('file1.csv', 'w') as f:
    rows = [['col1','col2','col3','col4']] + l1
    writer = csv.writer(f)
    writer.writerows(rows)

答案 1 :(得分:0)

CSV文件列由COMMA(,)分隔,因此您可以迭代数据结构并将以下文本打印到文件中:

NgSwitch

你可以用嵌套的for循环来实现它

col1,col2,co3,col4
http:/house.com/06,http:/google.com/09,http:6000.com,
http:/house.com/04,http:/google.com/03,http:600.com,http://900.com
http:/house.com/09,http:/google.com/076,http://rather.com,