Python格式处理--cvs表格

2021-06-18 18:09:01 浏览数 (1)

  1. import csv
  2. villains = [
  3. ['Doctor', 'No'],
  4. ['Rosa', 'Klebb'],
  5. ['Mister', 'Big'],
  6. ['Auric', 'Goldfinger'],
  7. ['Ernst', 'Blofeld'],
  8. ]
  9. with open('villains', 'wt') as fout: # 一个上下文管理器
  10.     csvout = csv.writer(fout)
  11.     csvout.writerows(villains)
  12. #读取cvs
  13. with open('villains', 'rt') as fin: # 一个上下文管理器
  14.     cin = csv.reader(fin)
  15.     villains = [row for row in cin] # 使用列表推导式
  16. print(villains)
  17. #读取成字典方式
  18. with open('villains', 'rt') as fin:
  19.     cin = csv.DictReader(fin, fieldnames=['first', 'last'])
  20.     villains = [row for row in cin]
  21. #将字典写入成标题在上面的方式
  22. villains = [
  23. {'first': 'Doctor', 'last': 'No'},
  24. {'first': 'Rosa', 'last': 'Klebb'},
  25. {'first': 'Mister', 'last': 'Big'},
  26. {'first': 'Auric', 'last': 'Goldfinger'},
  27. {'first': 'Ernst', 'last': 'Blofeld'},
  28. ]
  29. with open('villains', 'wt') as fout:
  30.   cout = csv.DictWriter(fout, ['first', 'last'])
  31.   cout.writeheader()
  32.   cout.writerows(villains)
  33. with open('villains', 'rt') as fin: #重头读取文件
  34.     cin = csv.DictReader(fin)
  35.     villains = [row for row in cin]

0 人点赞