CSV的簡單用法

  讀文件

import csv  
with open('test.csv','rb') as myFile:  
    lines=csv.reader(myFile)  
    for line in lines:  
        print line  

程序輸出:spa

['1', '2']
['3', 'a']
['4', 'b']3d

 

  寫文件

with open(r'C:\Users\asus\Desktop\frank.csv','w') as myFile:
    writer = csv.writer(myFile)
    writer.writerow(['frank', 'yangchao'])
    writer.writerows([('Bob','Tom'), ('liuwei', 'liuyong')])

 

  注意用csv的默認寫入時候,寫完一行會自動空行後再寫入,但添加中間的參數 newline='' 表示寫完一行接着寫第二行,中間不空行。同時參數‘r’,‘w’表示讀取的字符,‘rb’, 'wb'表示讀寫的字節code

with open(r'C:\Users\asus\Desktop\frank.csv','w', newline='') as myFile:
    writer = csv.writer(myFile)
    writer.writerow(['frank', 'yangchao'])
    writer.writerows([('Bob','Tom'), ('liuwei', 'liuyong')])

 

csv.DictWriter 與DictReader 讀寫文件

讀文件

文件以下:blog

DictReader會將第一行的內容(類標題)做爲key值,第二行開始纔是數據內容,第一列的key值爲name,第二列的key值爲class:it

import csv
with open(r'C:\Users\asus\Desktop\frank.csv','r') as myFile:
    reader = csv.DictReader(myFile)
    for row in reader:
        print(row['name'], row['class'])

輸出結果:
frank 135
tom 134
bob 141
ailsa 152

 

 寫文件
import csv
with open(r'C:\Users\asus\Desktop\frank.csv','w',newline='') as myFile:
    writer = csv.DictWriter(myFile, fieldnames=['name', 'address']) # 這裏注意,fieldname列表中的字段爲須要存入的字典的key,存入以後就存入key所對應的value
    writer.writeheader()
    writer.writerows([{'name':'Tom','address':'American'}, {'name':'Bob', 'address':'China'}])

 注意:writer.writeheader() 語句的做用是將 fieldnames=['name', 'address'] 中定義的標題(key)寫入到首行class

效果以下:test

相關文章
相關標籤/搜索