读文件
import csv with open('test.csv','rb') as myFile: lines=csv.reader(myFile) for line in lines: print line
程序输出:
['1', '2']
['3', 'a']
['4', 'b']
写文件
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'表示读写的字节
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 读写文件
读文件
文件如下:
DictReader会将第一行的内容(类标题)作为key值,第二行开始才是数据内容,第一列的key值为name,第二列的key值为class:
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所对应的valuewriter.writeheader()writer.writerows([{'name':'Tom','address':'American'}, {'name':'Bob', 'address':'China'}])
注意:writer.writeheader() 语句的作用是将 fieldnames=['name', 'address'] 中定义的标题(key)写入到首行
效果如下: