读取同一文件Python的多个行

Ret*_*sim 4 python for-loop file

我试图在Python中多次读取一些文件的行.

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

 with open(name, 'r+') as file:
                for line in file:
                    # Do Something with line
Run Code Online (Sandbox Code Playgroud)

这样工作正常,但是如果我想在每个行继续迭代,而我仍然打开我的文件,如:

 with open(name, 'r+') as file:
                for line in file:
                    # Do Something with line
                for line in file:
                    # Do Something with line, second time
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答!

Tim*_*ann 14

使用file.seek()跳转到文件中的特定位置.但是,请考虑是否真的有必要再次浏览该文件.也许有更好的选择.

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
Run Code Online (Sandbox Code Playgroud)