python 對csv檔案的操作十分簡單,幾行**即可搞定csv檔案,通常分為讀操作和寫操作。
讀取普通csv,不帶欄位名稱
示例**:
>>> import csv
>>> with open('test.csv', 'rb') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print ', '.join(row)
spam, spam, spam, spam, spam, baked beans
spam, lovely spam, wonderful spam
讀取帶欄位名稱的csv
例項**:
>>> import csv
>>> with open('names.csv') as csvfile:
... reader = csv.dictreader(csvfile) # 注意函式是大寫
... for row in reader:
... print(row['first_name'], row['last_name'])
...baked beans
lovely spam
wonderful spam
dictreader接收以下幾個引數:
寫普通csv檔案
示例**:
import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.quote_minimal)
spamwriter.writerow(['spam'] * 5 + ['baked beans'])
spamwriter.writerow(['spam', 'lovely spam', 'wonderful spam'])
基本上和reader一致。
寫帶欄位名稱的csv檔案
例項**:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.dictwriter(csvfile, fieldnames=fieldnames)
writer.writeheader() # 注意有寫header操作
writer.writerow()
writer.writerow()
writer.writerow()
dictwriter有幾個引數需要注意: Python csv檔案基本操作
摘錄自 python爬蟲開發與專案實戰 chapter5 csvtest.py import csv from collections import namedtuple namedtuple是繼承自tuple的子類。namedtuple建立乙個和tuple類似的物件,而且物件擁有可訪問的屬性。he...
python csv檔案的讀寫
csv檔案用於儲存 資料,可以用txt和excel開啟和編輯。寫入一次寫入一行,注意是使用list來裝要輸入的一行的內容。import csv import numpy as np out open data.csv w newline 防止每次輸入多空一行 writer csv.writer ou...
python CSV檔案處理
import csv 這種方式讀取到的每一條資料是乙個列表,所以需要通過下標的方式獲取具體某乙個值 with open stock.csv r encoding gbk as fp reader csv.reader fp for x in reader print x 3 這種方式讀取到的每一條資...