【原文链接】
csv写文件
csv.writer(f) 获取csv的write
writerow 写入一行数据
writerows 写入多行数据
注意打开文件的时候将 newline设置为“”,否则写的csv会存在空行
import csvdef main(): csv_file= "demo.csv" head=["name","age","sex"] data1=["zhangsan",20,"man"] data2=[ ["lisi",22,"man"], ["wangmei",18,"woman"] ] with open(csv_file,"a+",encoding="utf-8",newline="") as f: csv_writer=csv.writer(f) csv_writer.writerow(head) csv_writer.writerow(data1) csv_writer.writerows(data2)if __name__=="__main__": main()
csv读文件
import csvdef main(): csv_file= "demo.csv" with open(csv_file,"r",encoding="utf-8",newline="") as f: ctx=csv.reader(f) for row in ctx: print(row)if __name__=="__main__": main()
csv 写入数据为字典数据
注意初始化DictWriter的是就需要指定fieldnames
import csvdef main(): csv_file= "demo.csv" head=["name","age","sex"] data1={"name":"zhangsan","age":20,"sex":"man"} data2=[ {"name":"lisi","age":22,"sex":"man"}, {"name":"wangmei","age":18,"sex":"woman"} ] with open(csv_file,"a+",encoding="utf-8",newline="") as f: csv_writer=csv.DictWriter(f,fieldnames=head) csv_writer.writerow(data1) csv_writer.writerows(data2)if __name__=="__main__": main()
csv读取数据为字典数据
读取的时候初始化DictReader的时候不需要指定fieldnames,会自动将第一行作为fieldnames字段,然后读取出来
import csvdef main(): csv_file= "demo.csv" with open(csv_file,"r",encoding="utf-8",newline="") as f: ctx=csv.DictReader(f) for elem in ctx: print(elem)if __name__=="__main__": main()