import csv
header=['class','name','sex','height','year']
rows=[
[1,'xiaoming','male',168,23],
[1,'xiaohong','female',162,22],
[2,'xiaozhang','female',158,21],
[2,'xiaoli','male',158,21]
]
with open('csvdir.csv','w',newline='')as f: #newline=" "是为了避模歼侍免写入之后有空行
ff=csv.writer(f)
ff.writerow(header)
ff.writerows(rows)
2.在写入字典序列类型数据的时候,需要传入两个参数,一个是文件对象——f,一个是字段名称——fieldnames,到旦吵时候要写入表头的时候,只需要调用writerheader方法,写入一行字典系列数据调用writerrow方法,并传入相应字典参数,写入多行调用writerows
import csv
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('test2.csv','w',newline='')as f:
f_csv = csv.DictWriter(f,headers)
f_csv.writeheader()
f_csv.writerows(rows)
注意:列表和字典形式的数据写入是不一样的!!!!!!
3.csv的读取,和读取文件差不多:
import csv
with open('test.csv')as f:
f_csv = csv.reader(f)
for row in f_csv:
print(row)
1、报错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)写入csv时,设置为gbk格式,无需再转utf-8格式
import sys
reload(sys)
sys.setdefaultencoding('gbk')
登录后复制
2、把python里面的中文字符串decode成utf-8,再encode为gbk编码
data.decode('utf-8').encode('gbk')
如果是读取csv文件的话,亮大就反过来:
data.decode('gbk').encode('utf-8')
3、Pycharm控制台中纳键盯文输出乱码问题解决方案
设置完编码后,控制台扔乱码,也可能是设置字体导致的。
试了多次之后洞和,解决不了,重装Pycharm,然后就好了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)