c语言sscanf函数的用法是什么
274
2022-09-14
Python3以字典方式读写CSV
读取CSV
字典方式读取CSV(DictReader)
以字典方式读取CSV要保证表头是字典key。
import csvwith open("data.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader: print(row)
普通方式读取CSV
import csvwith open("data.csv", "r", encoding="utf-8") as f: reader = csv.reader(f) for row in reader: print(row)
字典方式转普通方式读取CSV
import csvwith open("data.csv", "r", encoding="utf-8") as f: reader = csv.DictReader(f) for row in reader.reader: print(row)
保存CSV
字典方式写CSV
import csvdata = [ {'Name': 'Mark', 'Age': 17, 'Sex': 'Male'}, {'Name': 'Lisa', 'Age': 16, 'Sex': 'Female'}, {'Name': 'Jacky', 'Age': 20, 'Sex': 'Male'},]with open('data.csv', 'w', newline='') as f: fieldnames = ['Name', 'Age', 'Sex'] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(data)
普通方式写CSV
import csvdata = [ ('Name', 'Age', 'Sex'), ('Jane', '16', 'Female'), ('Tom', '14', 'Male'), ('Leon', '15', 'Male'),]with open('data.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(data)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~