Why does the '_io.TextIOWrapper' object lack the 'xreadlines' method?
- 内容介绍
- 文章标签
- 相关推荐
本文共计359个文字,预计阅读时间需要2分钟。
Python 报错!`AttributeError`:`_io.TextIOWrapper` 对象没有 `xreadlines` 属性。错误信息如下:
Traceback (most recent call last): File countline.py, line 33, in module totalline=totalline + countLine(filelist) File countline.py, line 23, 在 countLine 函数中
这可能是因为你尝试在不再支持 `xreadlines()` 方法的 Python 版本中使用它。`xreadlines()` 方法在 Python 3 中已被移除,应该使用 `iterlines()` 或直接使用 `for` 循环来迭代文件对象。
Python 错误!AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'
Traceback (most recent call last):
File "countline.py", line 33, in <module>
totalline = totalline + countLine(filelist)
File "countline.py", line 23, in countLine
for file_line in open(fname).xreadlines():
AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'
原因:
- 在Python 2里,文件对象有一个xreadlines()方法,它返回一个迭代器,一次读取文件的一行。这在for循环中尤其有用。事实上,后来的Python 2版本给文件对象本身添加了这样的功能。
- 在Python 3里,xreadlines()方法不再可用了。
解决方法:
for file_line in open(fname).xreadlines():
改为:for file_line in open(fname, encoding="utf-8").readlines():
加上utf-8就不会乱码了。
若有帮助到您,欢迎点击推荐,您的支持是对我坚持最好的肯定(*^_^*)
你要保守你心,胜过保守一切。
作者:刘俊涛的博客
本文共计359个文字,预计阅读时间需要2分钟。
Python 报错!`AttributeError`:`_io.TextIOWrapper` 对象没有 `xreadlines` 属性。错误信息如下:
Traceback (most recent call last): File countline.py, line 33, in module totalline=totalline + countLine(filelist) File countline.py, line 23, 在 countLine 函数中
这可能是因为你尝试在不再支持 `xreadlines()` 方法的 Python 版本中使用它。`xreadlines()` 方法在 Python 3 中已被移除,应该使用 `iterlines()` 或直接使用 `for` 循环来迭代文件对象。
Python 错误!AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'
Traceback (most recent call last):
File "countline.py", line 33, in <module>
totalline = totalline + countLine(filelist)
File "countline.py", line 23, in countLine
for file_line in open(fname).xreadlines():
AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'
原因:
- 在Python 2里,文件对象有一个xreadlines()方法,它返回一个迭代器,一次读取文件的一行。这在for循环中尤其有用。事实上,后来的Python 2版本给文件对象本身添加了这样的功能。
- 在Python 3里,xreadlines()方法不再可用了。
解决方法:
for file_line in open(fname).xreadlines():
改为:for file_line in open(fname, encoding="utf-8").readlines():
加上utf-8就不会乱码了。
若有帮助到您,欢迎点击推荐,您的支持是对我坚持最好的肯定(*^_^*)
你要保守你心,胜过保守一切。
作者:刘俊涛的博客

