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. ['xe5xa7x93xe5x90x8d', 'xe5xb9xb4xe9xbex84', 'xe7x94xb5xe8xafx9d']
  3. ['xe5xb0x8fxe6xb2xb3', '25', '1234567']
  4. ['xe5xb0x8fxe8x8axb3', '18', '789456']



原文地址:https://www.cnblogs.com/snifferhu/p/4616288.html