**摘錄自《python爬蟲開發與專案實戰》chapter5
csvtest.py
import csv
from collections import namedtuple # namedtuple是繼承自tuple的子類。namedtuple建立乙個和tuple類似的物件,而且物件擁有可訪問的屬性。
headers = ['id', 'username', 'password', 'age', 'country']
rows = [(1001, "qiye", "qiye_pass", "24", "china"),(1002, "mark", "mark_pass", "24", "usa"),(1003, "alice", "alice_pass", "24", "usa")]
rows1 = [,,]
with open('qiye.csv', 'w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
with open('qiye1.csv', 'w') as f2:
# 以字典的形式寫檔案
f2_csv = csv.dictwriter(f2,headers)
f2_csv.writeheader()
f2_csv.writerows(rows1)
with open('qiye.csv') as f :
f_csv = csv.reader(f)
headers = next(f_csv)
print(headers)
row = namedtuple('row', headers) # 定義了乙個row類,包含header中的5個屬性
for r in f_csv:
print(r) #
if len(r)!=0 :
#用list建立了乙個row的物件,對該類中的屬性賦值。
row = row(*r) # 輸出 ['1001', 'qiye', 'qiye_pass', '24', 'china']
print(row.username, row.password) # 輸出 qiye qiye_pass
print(row) # 輸出 row(id='1001', username='qiye', password='qiye_pass', age='24', country='china')
with open('qiye.csv') as f1:
#以字典的形式讀取檔案
f_csv = csv.dictreader(f1)
for row in f_csv:
print(row.get('username')) # 輸出qiye
輸出:
python csv檔案的操作
python 對csv檔案的操作十分簡單,幾行 即可搞定csv檔案,通常分為讀操作和寫操作。讀取普通csv,不帶欄位名稱 示例 import csv with open test.csv rb as csvfile spamreader csv.reader csvfile,delimiter qu...
python csv一些基本操作總結
csv.reader csv.reader傳入的可以是列表或者檔案物件,返回的是乙個可迭代的物件,需要使用for迴圈遍歷 path c users a539 desktop 1.csv with open path,r as fp lines csv.reader fp for line in li...
python CSV檔案處理
import csv 這種方式讀取到的每一條資料是乙個列表,所以需要通過下標的方式獲取具體某乙個值 with open stock.csv r encoding gbk as fp reader csv.reader fp for x in reader print x 3 這種方式讀取到的每一條資...