多读取同一文件Python的多行 [英] Read multiple times lines of the same file Python

查看:129
本文介绍了多读取同一文件Python的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用这种基本的方式:

$ pre $ 用open(name,'r +')作为文件:
用于文件中的行:
#做某事与行

而且工作正常,但是如果我想每次迭代第二行时,仍然打开我的文件:

 以open(name,'r +')作为文件:
用于文件中的行:
#做一些行
作为文件中的行:
#做一些行,第二次

然后它不起作用,我需要打开,然后关闭,然后再打开我的文件,使其工作。

 打开(名称,'r +')作为文件:
作为文件中的行:
#做与行
打开(名称,'r +')文件:
在文件中的行:
#做一些行

谢谢为解答!

解决方案

使用 file.seek()跳转到文件中的特定位置。但是,想想是否有必要再次通过文件。也许有更好的选择。

 以open(name,'r +')作为文件:
for line in文件:
#做一些行
file.seek(0)
行中的文件:
#做某些行,第二次


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

Thanks for answers !

解决方案

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屋!

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