简体   繁体   English

连续两次使用“readlines()”

[英]Using "readlines()" twice in a row

I'm trying to do something like this:我正在尝试做这样的事情:

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

but the second time Lines is empty.但第二次Lines是空的。 Is that normal?这是正常的吗?

Yes, because .readlines() advances the file pointer to the end of the file.是的,因为.readlines()将文件指针推进到文件末尾。

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 .) (请注意, list()调用是创建列表副本所必需的,以便对Lines修改不会影响file_lines 。)

You need to reset the file pointer using您需要使用重置文件指针

file.seek(0)

before using使用前

file.readlines()

again.再次。

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:为了不必一次又一次地使用seek方法每次重置,请使用readlines方法,但您必须将其存储在变量中,如下例所示:

%%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!']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM