【问题标题】:Read multiple times lines of the same file Python [duplicate]读取同一文件Python的多次行[重复]
【发布时间】:2014-12-05 08:34:19
【问题描述】:

我试图在 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

感谢您的回答!

【问题讨论】:

    标签: python file for-loop


    【解决方案1】:

    使用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
    

    【讨论】:

    • 谢谢,一切正常!现在我们需要多次遍历整个文件,因为我们使用第一次迭代中的值来执行第二次迭代,这有点棘手,但我们也制作了一个更好的版本,只迭代一次,但我想要这是出于调试目的,我们实际迭代槽的文件没有使用相同的结构,它非常随机,我们需要首先正确迭代的值永远不会在相同的行号,我们不能使用 linecache 或 islice。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2020-07-10
    • 2012-12-04
    • 2012-12-31
    • 2021-05-25
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多