读取同一文件 Python 的多次行 [英] Read multiple times lines of the same file Python
本文介绍了读取同一文件 Python 的多次行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 Python 中多次读取某些文件的行.
I'm trying to read lines of some files multiple times in Python.
我正在使用这种基本方式:
I'm using this basic way :
with open(name, 'r+') as file:
for line in file:
# Do Something with line
这工作正常,但是如果我想在我的文件仍然打开的情况下对每一行进行第二次迭代:
And that's working fine, but if I want to iterate a second time each lines while I'm still with my file open like :
with open(name, 'r+') as file:
for line in file:
# Do Something with line
for line in file:
# Do Something with line, second time
然后它不起作用,我需要打开,然后关闭,然后再次打开我的文件以使其工作.
Then it doesn't work and I need to open, then close, then open again my file to make it work.
with open(name, 'r+') as file:
for line in file:
# Do Something with line
with open(name, 'r+') as file:
for line in file:
# Do Something with line
感谢您的回答!
推荐答案
使用 file.seek() 跳转到文件中的特定位置.不过,想想是否真的有必要再次通过文件.也许有更好的选择.
Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. Maybe there is a better option.
with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time
这篇关于读取同一文件 Python 的多次行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文