python中readlines,在python中连续两次使用readlines -凯发k8官方网
凯发k8官方网
收集整理的这篇文章主要介绍了
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?
凯发k8官方网的解决方案
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.)
总结
以上是凯发k8官方网为你收集整理的python中readlines,在python中连续两次使用readlines的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: