读取同一文件Python的多个行

时间:2014-10-10 08:21:37

标签: python file for-loop

我试图在Python中多次读取某些文件的行。

我使用这种基本方式:

 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
                for line in file:
                    # Do Something with line, second time

然后它无法正常工作,我需要打开,然后关闭,然后再次打开我的文件以使其正常工作。

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

感谢您的回答!

1 个答案:

答案 0 :(得分: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