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


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就不會亂碼了。

 

文章來源:劉俊濤的博客 歡迎關注公眾號、留言、評論,一起學習。

 

若有幫助到您,歡迎點擊推薦,您的支持是對我堅持最好的肯定(*^_^*)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM