python的csv库如何写成多列数据?

用csv库写入两列数据,但是却出现place列的部分数据会跑到name里面,place还有很多空值,这是为什么呢?
clipboard.png

我的代码如下:

import csv

name=['lucy','jacky','eric','man','san']
place=['chongqing','guangzhou','beijing','shanghai','shenzhen']

with open('credit_test.csv','w') as file:
    file.write('name,place\n')
    file.write("{name},{place}\n".format(name='\n'.join(name),place='\n'.join(place)))
阅读 10.1k
2 个回答

既然 import csv,就用 csv 来写啊~


python3

import csv
name=['lucy','jacky','eric','man','san']
place=['chongqing','guangzhou','beijing','shanghai','shenzhen']
with open('credit_test.csv','w') as file:
    w = csv.writer(file)
    w.writerow(('name','place'))
    w.writerows(zip(name,place))

原因是你把换行写到了每个name的后面。这个格式是错的。

name=['lucy','jacky','eric','man','san']
place=['chongqing','guangzhou','beijing','shanghai','shenzhen']

with open('credit_test.csv','w') as file:
    file.write('name,place\n')
    for n,p in zip(name,place):
        file.write("{},{}\n".format(n,p))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏