在Python中连续两次使用readlines [英] using readlines twice in a row in Python

查看:1121
本文介绍了在Python中连续两次使用readlines的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做这样的事情

I'm trying to do something like this

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

但第二次Line为空。这是正常的吗?

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

推荐答案

是的,因为 .readlines()预付款指向文件末尾的文件指针。

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)

它比击中磁盘两倍效率更高。 (注意, list()调用是创建列表副本以便修改 Lines 赢得'的必要条件。影响 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.)

这篇关于在Python中连续两次使用readlines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆