Python csv 写入及 csv写入中文乱码
1. csv 写入
CSV文件写入
第一种方式:列表
第二种方式:字典
1.1 列表
''' csv文件写入 第一种方式:列表 第二种方式:字典 ''' import csv header = ['学号', '姓名', "年龄", "性别", "地址"] student_info = [ ['01', '赵光明', '18', '女', '光明路1号'], ['02', '钱仁义', '18', '男', '仁义路2号'], ['03', '孙解放', '18', '女', '解放路3号'] ] filepath = r"C:\Users\*****\Desktop\student_info.csv" with open(filepath, mode= 'w', encoding='utf-8',newline='') as f: # newline='' 解决空行问题 writer = csv.writer(f) # 创建一个csv写入器 (对象) writer.writerow(header) # 写入表头 writer.writerows(student_info) # 写入内容. 列表中的一个元素(列表或元组) 对应一行
结果
1.2 字典
''' csv文件写入 第一种方式:列表 第二种方式:字典 ''' import csv header = ['学号', '姓名', "年龄", "性别", "地址"] student_info = [ {'学号': '01', '姓名': '赵光明', '年龄': '18', '性别': '女', '地址': '光明路1号'}, {'学号': '02', '姓名': '钱仁义', '年龄': '18', '性别': '男', '地址': '仁义路2号'}, {'学号': '03', '姓名': '孙解放', '年龄': '18', '性别': '女', '地址': '解放路3号'} ] filepath = r"C:\Users\*****\Desktop\student_info.csv" with open(filepath, mode='w',encoding = 'utf-8', newline='') as f: writer = csv.DictWriter(f,header) writer.writeheader() # 写入表头 writer.writerows(student_info) # 写入内容, 列表中一个元素(字典) 一行
结果:
2. csv写入中文乱码
设置: encoding = 'utf-8-sig'
钟声敲响了日落,柏油路跃过山坡,一直通向北方的是我们想象,长大后也未曾经过~