AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'

来源:互联网 发布:windows怎么更新系统 编辑:程序博客网 时间:2024/06/11 10:50

CSDN:http://blog.csdn.net/kicilove/article/
github:https://github.com/zhaohuicici?tab=repositories

问题:

AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'

原因:

AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘xreadlines’

I/O方法xreadlines()

  • 在Python 2里,文件对象有一个xreadlines()方法,它返回一个迭代器,一次读取文件的一行。这在for循环中尤其有用。事实上,后来的Python 2版本给文件对象本身添加了这样的功能。
  • 在Python 3里,xreadlines()方法不再可用了。2to3可以解决简单的情况,但是一些边缘案例则需要人工介入。

如果你以前使用一个参数(每次读取的行数)调用xreadlines(),2to3不能为你完成从Python 2到Python 3的转换,你的代码会以这样的方式失败:AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘xreadlines’。

解决方法:

你可以xreadlines()readlines()使Python3。(readline()方法在Python 3里返回迭代器,所以它跟Python 2里的xreadlines()效率是不相上下的。)

f= open('train.txt','rb')#将xreadlines改成readlines之后print (f.readlines())for line in f.readlines() :    print (line) f.close()'''#部分结果,发现乱码,这个时候该用read().decode('utf-8')可以显示正常结果啦。'''[b'0\t\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f\xe7\xab\x8b\xe5\xa4\x8f\xe4\xba\x86\xef\xbc\x8c\xe5\xbf\x83\xe4\xb8\xad\xe5\x8f\x88\xe6\x8a\x8a\xe4\xbd\xa0\xe6\x83\xb3\xe8\xb5\xb7\xe3\x80\x82\xe6\x84\xbf\xe4\xbc\x9a\xe5\xbf\x83\xe7\x9a\x84\xe5\xbe\xae\xe7\xac\x91\xef\xbc\x8c\xe6\x8e\x92\xe6\xbb\xa1\xe4\xbd\xa0\xe6\xaf\x8f\xe5\xa4\xa9\xe7\x9a\x84\xe6\x97\xa5\xe5\x8e\x86\xef\xbc\x9b\xe6\x8a\x9b\xe5\xbc\x83\xe5\x8e\x8b\xe5\x8a\x9b\xef\xbc\x8c\xe5\xa9\xb4\xe5\x84\xbf\xe8\x88\xac\xe6\x83\xac\xe6\x84\x8f\xe5\x9c\xb0\xe5\x91\xbc\xe5\x90\xb8\xef\xbc\x9b\xe5\xa4\xa9\xe6\xb0\x94\xe8\xbd\xac\xe7\x83\xad\xef\xbc\x8c\xe5\x88\xab\xe5\xbf\x98\xe5\xa5\xbd\xe5

CSDN:http://blog.csdn.net/kicilove/article/
github:https://github.com/zhaohuicici?tab=repositories

阅读全文
0 0
原创粉丝点击