python2 open encoding,在python 2.x中,'encoding是无效的关键字'错误是不可避免的吗?...

I tried the answer there to convert ansi to utf-8.

import io

with io.open(file_path_ansi, encoding='latin-1', errors='ignore') as source:

with open(file_path_utf8, mode='w', encoding='utf-8') as target:

shutil.copyfileobj(source, target)

But I got "TypeError: 'encoding' is an invalid keyword argument for this function"

I tried with

with io.open(file_path_ansi, encoding='cp1252', errors='ignore') as source:

, too, and got same error.

Then I tried

import io

with io.open(file_path_ansi, encoding='latin-1', errors='ignore') as source:

with io.open(file_path_utf8, mode='w', encoding='utf-8') as target:

shutil.copyfileobj(source, target)

and still got the same error. Also I tried with cp1252, too, but got the same error.

I learned from several stackoverflow questions that

TypeError: 'encoding' is an invalid keyword argument for this function

is frequently arising error message in python 2.x

But mainly answerers were suggesting using python 3 in some way or the other.

Is it really impossible to convert ansi txt to utf-8 txt in python 2.x ? (I use 2.7)

解决方案

For Python2.7, Use io.open() in both locations.

import io

import shutil

with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source:

with io.open('/tmp/goof', mode='w', encoding='utf-8') as target:

shutil.copyfileobj(source, target)

The above program runs without errors on my PC.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值