python csv一些基本操作總結(jié)
csv.reader
csv.reader傳入的可以是列表或者文件對(duì)象,返回的是一個(gè)可迭代的對(duì)象,需要使用for循環(huán)遍歷
path = 'C:UsersA539Desktop1.csv'with open(path, ’r’) as fp: lines = csv.reader(fp) for line in lines:print(line) print(type(line))
line的格式為list
csv.writer
將一個(gè)列表寫入csv文件
list1 = [100, 200, 300, 400, 500]list2 = [[500, 600, 700, 800, 900], [50, 60, 70, 80, 90]]with open(path, ’w’,newline=’’)as fp: writer = csv.writer(fp) # 寫入一行 writer.writerow(list1) # 寫入多行 writer.writerows(list2)
不加newline = ’’會(huì)導(dǎo)致每行之間有一行空行
csv.DictWriter
寫入字典
head = [’aa’, ’bb’, ’cc’, ’dd’, ’ee’]lines = [{’aa’: 10 , ’bb’: 20, ’cc’: 30, ’dd’: 40, ’ee’: 50},{’aa’: 100, ’bb’: 200, ’cc’: 300, ’dd’: 400, ’ee’: 500},{’aa’: 1000, ’bb’: 2000, ’cc’: 3000, ’dd’: 4000, ’ee’: 5000},{’aa’: 10000, ’bb’: 20000, ’cc’: 30000, ’dd’: 40000, ’ee’: 50000}, ]with open(path, ’w’,newline=’’)as fp: dictwriter = csv.DictWriter(fp, head) dictwriter.writeheader()
with open(path, ’w’, newline=’’)as fp: dictwriter = csv.DictWriter(fp, head) dictwriter.writeheader() dictwriter.writerows(lines)
不覆蓋原有內(nèi)容寫入
上述的寫入都會(huì)覆蓋原有的內(nèi)容,要想保存之前的內(nèi)容,將新內(nèi)容附加到后面,只需要更改標(biāo)志為’a+’
with open(path, ’a+’, newline=’’)as fp: dictwriter = csv.DictWriter(fp, head) dictwriter.writeheader() dictwriter.writerows(lines)
附
https://docs.python.org/2/library/csv.html#module-csv.
參考
csv模塊的使用
到此這篇關(guān)于python csv一些基本操作總結(jié)的文章就介紹到這了,更多相關(guān)csv基本操作內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. asp批量添加修改刪除操作示例代碼2. ASP實(shí)現(xiàn)加法驗(yàn)證碼3. PHP循環(huán)與分支知識(shí)點(diǎn)梳理4. 讀大數(shù)據(jù)量的XML文件的讀取問題5. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案6. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)7. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能8. 解析原生JS getComputedStyle9. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲10. css代碼優(yōu)化的12個(gè)技巧
