python 操作csv文件
写
with open('test3.csv','w',newline='')as f: write = csv.writer(f) write.writerow(['ww','rr','',2]) # 写入一行 write.writerows(['ww','rr','',2],['qq',''ww]) #多行 #字典的数据 headers = ['class','name','sex','height','year'] rows = [ {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23}, {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22}, {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21}, {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21}, ] with open('test3.csv','w',newline='')as f: f_csv = csv.DictWriter(f,headers) f_csv.writeheader() # 写入头信息 f_csv.writerows(rows) #写入value
读
with open('test2.csv')as f: f_csv = csv.reader(f) for row in f_csv: print(row) # 一行行获取 # print(list(f_csv)) # 直接获取列表数据 #[['class', 'name', 'sex', 'height', 'year'], ['1', 'xiaoming', 'male', '168', '23'] ]