Using “readlines()” twice in a row

点点圈 提交于 2019-11-26 22:12:22

问题


I'm trying to do something like this:

Lines = file.readlines()
# do something
Lines = file.readlines()  

but the second time Lines is empty. Is that normal?


回答1:


Yes, because .readlines() advances the file pointer to the end of the file.

Why not just store a copy of the lines in a variable?

file_lines = file.readlines()
Lines = list(file_lines)
# do something that modifies Lines
Lines = list(file_lines)

It'd be far more efficient than hitting the disk twice. (Note that the list() call is necessary to create a copy of the list so that modifications to Lines won't affect file_lines.)




回答2:


You need to reset the file pointer using

file.seek(0)

before using

file.readlines()

again.




回答3:


In order to not have to reset every time by using seek method again and again, use the readlines method, but you must store it in variable like this example below:

%%writefile test.txt
this is a test file!
#open it
op_file = open('test.txt')
#read the file
re_file = op_file.readlines()
re_file
#output
['this is a test file!']
# the output still the same
re_file
['this is a test file!']


来源:https://stackoverflow.com/questions/10201008/using-readlines-twice-in-a-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!