python中readlines,在Python中连续两次使用readlines
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.)
總結
以上是生活随笔為你收集整理的python中readlines,在Python中连续两次使用readlines的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 服务器配置文档查服务器名称,服务器配置答
- 下一篇: 微信摇一摇插件ios_微信开发平台 Je