利用Python写入CSV文件的方法

  第一种:CSV写入中文

#! /usr/bin/env python
# _*_  coding:utf-8 _*_

import csv
csvfile = file('test.csv', 'wb')
csvfile.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(csvfile)
writer.writerow(['id', 'url', 'keywords'])
data = [
  ('1', 'http://www.baidu.com/', '百度'),
  ('2', 'http://www.taobao.com/', '淘宝'),
  ('3', 'http://www.jd.com/', '京东')
]
writer.writerows(data)
csvfile.close()

运行截图:

 第二种:

利用unicodecsv 将中文写入csv文件:

#!/usr/bin/python
# -*- coding:utf-8 -*- 

import unicodecsv as ucsv
data = [[u"列1", u"列2"], [u"内容1", u"内容2"]]
with open('test.csv', 'wb') as f:
    w = ucsv.writer(f, encoding = 'gbk')
    w.writerows(data)

运行后,用excel打开的效果:

 

 

参考链接:https://www.jb51.net/article/132732.htm

posted @ 2019-03-07 13:22  Bypass  阅读(28306)  评论(0编辑  收藏  举报