【问题标题】:Python read text file and keep it open [duplicate]Python读取文本文件并保持打开状态[重复]
【发布时间】:2015-10-21 03:53:52
【问题描述】:

我有一个用 Python 读入的文本文件,然后我确定包含特定关键字的行号。由于某种原因,我发现每次搜索不同的关键字时都必须打开文件。我尝试使用 with 语句来保持文件打开,但这似乎不起作用。

在下面的示例中,我找到了文件中最后一行的行号以及包含字符串“Results”的第一行

with open(MyFile,'r') as f:
    lastline = sum(1 for line in f)

    for num, line in enumerate(f): 
        if 'Results' in line:
            ResultLine=num   
            break

这成功地完成了第一个操作(确定最后一行),但不是后者。如果我只是打开文件两次,它可以工作:

f=open(MyFile, 'r')
lastline = sum(1 for line in f)

f=open(MyFile, 'r')      
for num, line in enumerate(f): 
    if 'Results' in line:
        ResultLine=num   
        break

关于为什么我的 with 语句不能保持文件打开的任何建议?

感谢您的帮助。

【问题讨论】:

    标签: python


    【解决方案1】:

    如果你想处理同一个文件,你需要倒回文件指针。只需在第二次枚举之前执行f.seek(0)

    然而,进入你的代码实际在做什么,它可以被优化为在同一个循环中做所有事情

    with open(MyFile,'r') as f:
        lastline = 0
        ResultLine = None
    
        for num, line in enumerate(f): 
            if not ResultLine and 'Results' in line:
                ResultLine=num
    
        lastline = num # + 1 if you want a count; this is what you actually get 
                       # in your sample, the count, not the last line index
    

    【讨论】:

    • 无需每次循环都重新分配lastline
    【解决方案2】:

    with 创建一个contextmanager

    contextmanagers 会在你退出他们的作用域后自动清理...(即关闭文件句柄)

    此答案仅解决了退出 with 语句时文件句柄关闭的原因

    有关with 语句和上下文管理器的更多信息,请参阅http://preshing.com/20110920/the-python-with-statement-by-example/(在谷歌上搜索“文件上下文管理器”时出现的第一个链接)

    【讨论】:

      【解决方案3】:

      尝试一次通过文件同时完成这两项任务:

      with open(MyFile,'r') as f:
          searching = True
          for num, line in enumerate(f): 
              if searching and 'Results' in line:
                  ResultLine=num
                  searching = False
          lastline = num
      

      【讨论】:

        【解决方案4】:
        with open(MyFile,'r') as f:
            lastline = sum(1 for line in f)
        
            ## The pointer f has reached the end of the file here
            ## Need to reset pointer back to beginning
            f.seek(0)
        
            for num, line in enumerate(f): 
                if 'Results' in line:
                    ResultLine=num   
                    break
        

        【讨论】:

          【解决方案5】:

          问题是您已经有效地读取了整个文件一次,所以当您转到 enumerate 行时,没有什么可以提取的了。

          您应该一次阅读所有行,然后评估 那个

          f = open(MyFile, 'r')
          lines = list(f)
          
          # operate on lines instead of f!
          # ...
          

          【讨论】:

            猜你喜欢
            • 2011-11-16
            • 2019-01-03
            • 2011-04-24
            • 1970-01-01
            • 1970-01-01
            • 2017-11-01
            • 1970-01-01
            • 2016-06-23
            • 2011-03-09
            相关资源
            最近更新 更多