1.讀取html
第一種:post
import csv with open("route.csv","r") as f: #reader是一個迭代器 reader=csv.reader(f) next(reader) #輸出結果會去掉行頭標題 for row in reader: name=row[0] dates=row[-1] print({"name":name,"date":dates})
第二種:字典方式讀取url
import csv with open("route.csv","r") as f: #使用DictReader建立的reader是一個迭代器,遍歷迭代器返回的數據是一個字典(有序字典) #返回的結果不包含行首的標題 reader=csv.DictReader(f) for row in reader: # print(row) #遍歷迭代器返回的數據是一個字典(有序字典) print(row["暱稱"],row["院系信息"])
2.寫入code
第一種:htm
import csv headers=["username","age","addr"] values={ ("張三",23,"滿城"), ("李四",24,"保定"), ("王五",25,"衡水"), ("趙六",26,"邯鄲") } with open("name.csv","w",encoding="utf-8",newline="") as f: #newline換行符爲空,默認爲\n writer=csv.writer(f) writer.writerow(headers) #寫入行首標題 writer.writerows(values) #寫入多行
第二種:blog
import csv headers=["username","age","addr"] values=[ {"username":"張三","age":23,"addr":"保定"}, {"username":"李四","age":23,"addr":"邯鄲"}, {"username":"王五","age":23,"addr":"石家莊"}, {"username":"趙六","age":23,"addr":"衡水"}, ] with open("name2.csv","w",encoding="utf-8",newline="") as f: writer=csv.DictWriter(f,headers) #寫入表頭的時候須要寫入writerheader方法 writer.writeheader() writer.writerows(values)