python3读取文件样例:
file=open("/xx/xx/xx/xx/ids/"+res_db+"_"+res_tb+".txt")
read_flag=0
for id in file.xreadlines():
exesql="update users set updated_time='2019-01-01 00:30:00' where pkid=%s"%(id)
运行报错,信息如下:
AttributeError: '_io.TextIOWrapper' object has no attribute 'xreadlines'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()方法不再可用了。python2环境转成python3环境可以解决简单的情况,但是一些边缘案例则需要人工重新调试运行
解决方法:
手工的把xreadlines()改成readlines()以使代码能在Python3下工作手工的把xreadlines()改成readlines()以使代码能在Python3下工作。(readline()方法在Python 3里返回迭代器,所以它跟Python 2里的xreadlines()效率是不相上下的。)
读取多少行,退出:
read_flag=0
file=open("/xx/xx/xx/xx/ids/"+res_db+"_"+res_tb+".txt")
for id in file.readlines():
read_flag += 1
if read_flag<1000: print("continue to read line")
else:print("file read quit");file.close();return 0