首页 > 编程知识 正文

python中readlines的用法,python的readlines函数

时间:2023-05-04 10:49:16 阅读:236086 作者:1749

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?

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。