python 读写CSV文件

#-*- coding: UTF-8 -*-
import csv
import os
def WriteToCsv():
  '''写CSV文件'''
  titls = ['序号', '链接', '备注']
  data = [
    ['1', 'http://www.xiaoheiseo.com/', '小黑'],
    ['2', 'http://www.baidu.com/', '百度'],
    ['3', 'http://www.jd.com/', '京东']
  ]
  csvfile = os.path.join(os.getcwd(),'csvtest.csv')
  with open(csvfile, 'wb') as f:
    writer = csv.writer(f)
    # 标题
    writer.writerow(titls)
    # 内容
    writer.writerows(data)

def ReadCSV():
  '''读取CSV文件'''
  filename = os.path.join(os.getcwd(), 'csvtest.csv')
  if os.path.exists(filename):
    with open(filename, 'r') as f:
      reader = csv.reader(f)
      for item in reader:
        print item

# WriteToCsv()
# ReadCSV()

 上述代码,打开CSV文件,现在正常,但是在别人机器上打开是乱码,后来在网上查下,下加两行代码就了

首先引入

import codecs
然后增加
f.write(codecs.BOM_UTF8)
完整代码如下:
#-*- coding: UTF-8 -*-
import csv
import os
import codecs

def WriteToCsv():
  '''写CSV文件'''
  titls = ['序号', '链接', '备注']
  data = [
    ['1', 'http://www.xiaoheiseo.com/', '小黑'],
    ['2', 'http://www.baidu.com/', '百度'],
    ['3', 'http://www.jd.com/', '京东']
  ]
  csvfile = os.path.join(os.getcwd(),'csvtest.csv')
  with open(csvfile, 'wb') as f:
    f.write(codecs.BOM_UTF8)
    writer = csv.writer(f)
    # 标题
    writer.writerow(titls)
    # 内容
    writer.writerows(data)

def ReadCSV():
  '''读取CSV文件'''
  filename = os.path.join(os.getcwd(), './data/20170708.csv')
  if os.path.exists(filename):
    with open(filename, 'r') as f:
      reader = csv.reader(f)
      for item in reader:
        print item

# WriteToCsv()
# ReadCSV()

 

posted on 2016-07-19 16:21  shaomine  阅读(3578)  评论(0编辑  收藏  举报