Python讀寫csv檔案

來源:互聯網
上載者:User

標籤:

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. [email protected]-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)

Python讀寫csv檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.