如何读取文本文件并使用 python 检查其内容
How to read a text file and check against its contents with python
我正在尝试读取文本文件,打印其内容,并在到达 "flag" 时停止。
我的代码是:
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
有问题的文本文件里面只有这个没有多余的空格或者returns:
this is the ip
this is the /24
this is the gateway
this is the name server
break
循环将无限地继续 运行,我不确定如何正确分配变量以使其正确检查。
从文本文件中读取时,python不会分配原始字符串值吗?我在这里做错了什么?
尝试类似的东西,
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
虽然许多答案对我遇到的其他问题非常有帮助,但 none 明确回答了这个问题。
我已经使用 Mr.Mean's suggestion of .replace to clear up the hidden characters that are returned in text documents. Another user 向我展示了 .strip()(我应该知道的东西),它对 strip 隐藏字符的效果更好。
当阅读 Python 中的文本文档时,如果按回车换行,将会出现看不见的
\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
除非有人另有建议,否则我最终会接受这个答案。
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
我正在尝试读取文本文件,打印其内容,并在到达 "flag" 时停止。
我的代码是:
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
有问题的文本文件里面只有这个没有多余的空格或者returns:
this is the ip
this is the /24
this is the gateway
this is the name server
break
循环将无限地继续 运行,我不确定如何正确分配变量以使其正确检查。
从文本文件中读取时,python不会分配原始字符串值吗?我在这里做错了什么?
尝试类似的东西,
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
虽然许多答案对我遇到的其他问题非常有帮助,但 none 明确回答了这个问题。
我已经使用 Mr.Mean's suggestion of .replace to clear up the hidden characters that are returned in text documents. Another user 向我展示了 .strip()(我应该知道的东西),它对 strip 隐藏字符的效果更好。
当阅读 Python 中的文本文档时,如果按回车换行,将会出现看不见的
\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
除非有人另有建议,否则我最终会接受这个答案。
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