潦草白纸

Python读写csv文件

1. 写入并生成csv文件
代码:
  1. # coding: utf-8

  2. import csv

  3. csvfile = file('csv_test.csv', 'wb')
  4. writer = csv.writer(csvfile)
  5. writer.writerow(['姓名', '年龄', '电话'])

  6. data = [
  7.     ('小河', '25', '1234567'),
  8.     ('小芳', '18', '789456')
  9. ]
  10. writer.writerows(data)

  11. csvfile.close()
  • wb中的w表示写入模式,b是文件模式
  • 写入一行用writerow
  • 多行用writerows
2. 读取csv文件
代码:
  1. # coding: utf-8

  2. import csv

  3. csvfile = file('csv_test.csv', 'rb')
  4. reader = csv.reader(csvfile)

  5. for line in reader:
  6.     print line

  7. csvfile.close() 
运行结果:
  1. root@he-desktop:~/python/example# python read_csv.py 
  2. ['\xe5\xa7\x93\xe5\x90\x8d', '\xe5\xb9\xb4\xe9\xbe\x84', '\xe7\x94\xb5\xe8\xaf\x9d']
  3. ['\xe5\xb0\x8f\xe6\xb2\xb3', '25', '1234567']
  4. ['\xe5\xb0\x8f\xe8\x8a\xb3', '18', '789456']


来自为知笔记(Wiz)

posted on 2015-07-02 15:50  潦草白纸  阅读(498)  评论(0编辑  收藏  举报

导航