python csv一些基本操作總結
csv.reader
csv.reader傳入的可以是列表或者文件對象,返回的是一個可迭代的對象,需要使用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
將一個列表寫入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 = ’’會導致每行之間有一行空行
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)
不覆蓋原有內容寫入
上述的寫入都會覆蓋原有的內容,要想保存之前的內容,將新內容附加到后面,只需要更改標志為’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模塊的使用
到此這篇關于python csv一些基本操作總結的文章就介紹到這了,更多相關csv基本操作內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. java——Byte類/包裝類的使用說明2. android studio實現(xiàn)簡單的計算器(無bug)3. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作4. python Selenium 庫的使用技巧5. android 控件同時監(jiān)聽單擊和雙擊實例6. python+pywinauto+lackey實現(xiàn)PC端exe自動化的示例代碼7. vue使用exif獲取圖片經(jīng)緯度的示例代碼8. python logging.info在終端沒輸出的解決9. 詳解android adb常見用法10. Python 忽略文件名編碼的方法
