在 python 2.x 中,“编码是无效关键字"错误是不可避免的吗? [英] Is 'encoding is an invalid keyword' error inevitable in python 2.x?

查看:16
本文介绍了在 python 2.x 中,“编码是无效关键字"错误是不可避免的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ansi 到 UTF-8 使用 python 导致错误

我在那里尝试了将 ansi 转换为 utf-8 的答案.

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)

但是我得到TypeError: 'encoding' is an invalid keyword argument for this function"

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

我试过

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

也是,得到同样的错误.

, too, and got same error.

然后我尝试了

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)

仍然有同样的错误.我也尝试过 cp1252,但得到了同样的错误.

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

我从几个stackoverflow问题中了解到

I learned from several stackoverflow questions that

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

在python 2.x中经常出现错误信息

is frequently arising error message in python 2.x

但主要是回答者建议以某种方式使用 python 3.

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

在python 2.x中真的不能把ansi txt转utf-8 txt吗?(我用的是 2.7)

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

推荐答案

对于 Python2.7,在两个位置使用 io.open().

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.

这篇关于在 python 2.x 中,“编码是无效关键字"错误是不可避免的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆