【问题标题】:How to read a text file and check against its contents with python如何读取文本文件并使用 python 检查其内容
【发布时间】:2025-11-24 14:10:01
【问题描述】:

我正在尝试读取文本文件,打印其内容,并在到达“标志”时停止。

我的代码是:

 import sys
 sys.path.append("/Libraries/Documents")
 file = open("readmepython.txt", "r")
 while True:
     x = file.readline()
     if x != "break":
         print(x)
     else:
         break

 #doesnt work

有问题的文本文件里面只有这个,没有多余的空格或返回:

this is the ip
this is the /24
this is the gateway
this is the name server
break

循环将继续无限运行,我不确定如何正确分配变量以便正确检查。

从文本文件读取时,python 不分配原始字符串值吗?我在这里做错了什么?

【问题讨论】:

  • print(repr(x)) 在 readline 之后,您将自己看到问题。
  • 当您完成读取文件时,您是否有理由不只是将循环写入结束?即For line in file: print line ...
  • 这解释了我的文本文件的问题。我应该意识到存在返回字符。谢谢@MarkTolonen
  • @Mark_Eng 我正在练习我即将开展的项目所需的技能。检查文本文档中的错误是必要的。你是对的,仅仅阅读整个文件会容易得多:)
  • 仅供参考,file.readlines() 将一次性为您提供整个文件。如果您正在处理小文件,这可能是值得使用的东西(较大的文件可能会占用您系统上的太多资源)。

标签: python string text variable-assignment


【解决方案1】:

试试类似的,

file = open("readmepython.txt", "r")
For line in file:
   print line

file = open("readmepython.txt", "r")
For line in file.readlines():
    print line

另见:python looping through input file

【讨论】:

    【解决方案2】:
    import sys
    sys.path.append("/Libraries/Documents")
    file = open("readmepython.txt", "r")
    while True:
        x = file.readline().strip()
        if x != "break":
          print(x)
        else:
          break
    

    【讨论】:

      【解决方案3】:

      虽然许多答案对我遇到的其他问题非常有帮助,但没有人明确回答这个问题。 我使用了 Mr.Mean's 建议的 .replace 来清除文本文档中返回的隐藏字符。 Another user 向我展示了 .strip()(我应该知道的),它很有效最好剥离隐藏字符。

      在 Python 中读取文本文档时,如果按 Enter 换行,则会出现一个看不见的

      \n
      

      在字符串的末尾,用单引号' '括起来。

      我最终使用 .replace 方法两次将字符串清除为我想要的。这也可以通过分割字符串的第一个字符和最后三个字符来完成。

      我的新功能代码:

      import sys
      sys.path.append("/Libraries/Documents")
      file = open("readmepython.txt", "r")
      while True:
          x = file.readline().strip
          if x != "break":
            print(x)
          else:
            break
      
      #does work
      

      除非有人另有建议,否则我最终会接受这个答案。

      【讨论】:

      • 您还可以使用 x.strip() 去除字符串 docs.python.org/2/library/string.html#string.strip 开头和结尾的所有空格,因此,在您的情况下:x = file.readline().strip()
      • 太棒了!那要简单得多。 @joelgoldstick
      • @joelgoldstick 如果你想回答我很乐意接受这个回答