Using “readlines()” twice in a row

后端 未结 3 527
旧时难觅i
旧时难觅i 2020-11-30 15:22

I\'m trying to do something like this:

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

but the second time Lines

3条回答
  •  遥遥无期
    2020-11-30 16:14

    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.)

提交回复
热议问题