Python讀寫csv文件

1. 寫入並生成csv文件
代碼:
# coding: utf-8

import csv

csvfile = file('csv_test.csv', 'wb')
writer = csv.writer(csvfile)
writer.writerow(['姓名', '年齡', '電話'])

data = [
    ('小河', '25', '1234567'),
    ('小芳', '18', '789456')
]
writer.writerows(data)

csvfile.close()

  • wb中的w表示寫入模式,b是文件模式
  • 寫入一行用writerow
  • 多行用writerows

2. 讀取csv文件
代碼:
# coding: utf-8

import csv

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

for line in reader:
    print line

csvfile.close() 

運行結果:
root@he-desktop:~/python/example# python read_csv.py 
['\xe5\xa7\x93\xe5\x90\x8d', '\xe5\xb9\xb4\xe9\xbe\x84', '\xe7\x94\xb5\xe8\xaf\x9d']
['\xe5\xb0\x8f\xe6\xb2\xb3', '25', '1234567']
['\xe5\xb0\x8f\xe8\x8a\xb3', '18', '789456']

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章