python中open,io.open和codecs.open的使用——TypeError:'encoding' is an invalid keyword argument

问题描述:

python打开文件最简单的方法:f = open('test.txt', 'r')

但有时候我们要指定编码方式,例如 f=open('test.txt', 'r', encoding='utf-8'),如果是python3则没有问题,但如果是python2,则会报错:TypeError: 'encoding' is an invalid keyword argument for this function.

原因

Python 2的open实际上是file模块提供的,而Python 3的open是io模块提供的。然后,Python 2.6引入了这个Python 3的特性,叫做io.open,以便和原来的open相区分。

解决方法:

在python2下要指定编码方式打开文件,最好引入codecs,因为io.open有时候也会有一些奇怪的问题。

为了代码鲁棒性,建议在open打开文件时,统一引入codecs,使用codecs.open().

猜你喜欢

转载自blog.csdn.net/hongxingabc/article/details/82755538