【问题标题】:Check if a line exists in a file检查文件中是否存在一行
【发布时间】:2026-01-01 10:20:06
【问题描述】:

如何检查文件中是否存在一行?

如果文件不存在,我也想将该行写入文件。

这是我目前的尝试:

logfile = open('ip.log', 'a+')

while 1:
    line = logfile.readline()
    #line.replace("\n", "")
    print line
        
    if line == str(self.CLIENT_HOST):
        print "Line Found Skipping"
    else:
        logfile.write(str(self.CLIENT_HOST)+"\n")
    if not line:
        print "EOF Reached"
        break
    print line
logfile.close()

【问题讨论】:

  • 请注意,最好使用 readlines() 等内置函数并使用 for.. 语法。而(1)更容易出错。
  • 你根本不应该使用while 1:它是一个幻数使用。相反,如果需要使用 while True:.
  • @Andrej:我同意。然而,仅仅出于好奇,while 1: 实际上在 Python 2 中更有效,因为True 会进行查找(它不是 Python 3 中的保留字),而已知 1 是正确的 - 所以字节码的形成实际上并没有为while 1: 创建一个块。观察,创建你的函数并比较dis.dis(func)
  • @Chris:有趣!我记得曾经读过一次关于 True in python 的家谱,但我不知道这一点。我猜还有一个使用 Python3 的理由。

标签: python


【解决方案1】:
logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
    if str(self.CLIENT_HOST) in line:
        print "Found it"
        found = True

if not found:
    logfile = open('ip.log', 'a')
    logfile.write(str(self.CLIENT_HOST)+"\n")
    logfile.close()

这是我的第一个快速解决方案。非常不干净,还不成熟,但应该可以工作。

【讨论】:

  • 非常不干净,效率低下。
【解决方案2】:

我认为这应该可行,并且比其他任何答案都更整洁、更强大。如果没有,那么您可能需要打开另一个文件进行写入(第一个文件'r',第二个文件'a')。我也使用x.rstrip('\r\n')== 而不是in 来确保它是正确的。我不知道你的 CLIENT_HOST 变量是什么。如果您的CLIENT_HOST 已经是一个str,则丢弃第一行并将其他行改回直接引用它。

value = str(self.CLIENT_HOST)
with open('ip.log', 'a+') as f:
    if not any(value == x.rstrip('\r\n') for x in f):
        f.write(value + '\n')

【讨论】:

  • OS X 可能需要额外的 f.seek(0),因为文件指针在以“a+”模式打开后位于文件末尾。
  • 这实际上应该适用于所有操作系统。根据文档,文件指针位于文件末尾,至少对于 Python 3 docs.python.org/3/library/functions.html#open
【解决方案3】:

要在日志文件中附加一个客户端主机字符串(如果它不存在),您可以:

with open('ip.log', 'r+') as f:
     for line in f:
         if self.CLIENT_HOST in line:
            break
     else: # not found
         print >>f, self.CLIENT_HOST

注意:else 语句的缩进不是错误。这是一个 Python 功能,允许 forwhile 循环有一个 else 子句。如果break 语句未在循环内执行,则运行它。

【讨论】:

  • 完全被低估了,在我看来是经典的解决方案。谢谢。
  • mode 应该是 "r+" 和 "a+" 它在 Python3 中对我不起作用
  • @tamerlaha print >>f, .. 建议它是 Python 2 代码。虽然r+ 看起来应该更合适。
【解决方案4】:

使用python过滤器:

file = open('ip.log', 'r')
flines = file.readlines()
res = filter(lambda x: self.CLIENT_HOST in x, flines)
if len(res) == 0:
  file.write(str(self.CLIENT_HOST)+"\n")
  file.close()

【讨论】:

    【解决方案5】:

    将 open('ip.log', 'a+') 改为 open('ip.log', 'r'),然后稍后再写入文件或写入新文件。否则,您只是使文件无限长。

    【讨论】:

      【解决方案6】:

      遍历行允许您在找到匹配项时停止加载文件,并防止您将整个文件保存在内存中。

      def log_host(self):
          host = str(self.CLIENT_HOST)
      
          with open('ip.log', 'r+') as logfile:
              for line in logfile:
                  if line.strip() == host:
                      return
      
              # Move to the end of the file:
              logfile.seek(0, 2)
              logfile.write(host + "\n")
      

      【讨论】:

      • 你不是已经在文件末尾了,因为你只是读了每一行吗?
      【解决方案7】:

      可能是这样的

      line="the line you are searching for"
      
      logfile = open('ip.log', 'r')
      loglist = logfile.readlines()
      logfile.close()
      
      if line not in loglist:
          loglist.append(line)
      
      new_logfile = open("pathToTheFile/logfile", 'w')
      for lines in loglist:
          new_logfile.write(lines)
      

      【讨论】: