Python 3读写文件和Python2的区别

最近再看python处理csv的内容,查阅之前有python2 打开csv文件的操作:

writer = csv.writer (open('test.csv','wb')

但是在python3处理起来一直报错

TypeError: a bytes-like object is required, not 'str'


查阅文献后发现

n Python 2.X, it was required to open the csvfile with 'b' because the csv module does its own line termination handling.

In Python 3.X, the csv module still does its own line termination handling, but still needs to know an encoding for Unicode strings. The correct way to open a csv file for writing is:

发现在python2中要用二进制打开文件,进行line termination handling,但是在python3中,这种方式是不能用了

改成:

writer = csv.writer (open('test.csv','w',encoding='utf8',newline=''))
即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值