刚刚开始编程(Python),使用文本文件(x)的内容满足input()==x
使用Python,我试图将文本文件的内容设置为变量x,并使用if语句,通过使用用户输入(即s变量)创建一个简单的密码程序。但是,当我使用与text.txt文件相同的用户输入1234时,if语句失败并打印“拒绝访问”。任何帮助都将不胜感激刚刚开始编程(Python),使用文本文件(x)的内容满足input()==x,python,if-statement,Python,If Statement,使用Python,我试图将文本文件的内容设置为变量x,并使用if语句,通过使用用户输入(即s变量)创建一个简单的密码程序。但是,当我使用与text.txt文件相同的用户输入1234时,if语句失败并打印“拒绝访问”。任何帮助都将不胜感激 Here is my code: print ('Enter Password') s = input() #goal is to input '1234' x = open('text.txt','r') #text.txt contains '1234'
Here is my code:
print ('Enter Password')
s = input() #goal is to input '1234'
x = open('text.txt','r') #text.txt contains '1234'
print("you typed", s)
if s == x:
print("Access Granted")
else:
print("Access Denied")
在您的版本中,
x
是一个文件对象。要获取内容,您需要阅读它。把空白也去掉是个好主意
print ('Enter Password')
s = input() #goal is to input '1234'
x = open('text.txt','r').read().strip()
print("you typed", s)
if s == x:
print("Access Granted")
else:
print("Access Denied")
但现在您有了一个无法关闭的打开文件(Python通常会为您完成这项工作,但最好开始正确地完成这些工作)。通常的方法是将与
print ('Enter Password')
s = input() #goal is to input '1234'
with open('text.txt','r') as fin:
x = fin.read().strip()
print("you typed", s)
if s == x:
print("Access Granted")
else:
print("Access Denied")
现在,文件在
with
块(称为上下文管理器)的末尾自动关闭分配给变量x
的open
的输出将是一个文件对象
尝试打印x
,您将看到如下内容
<_io.TextIOWrapper name='text.txt' mode='r' encoding='UTF-8'>
text.txt
只需包含字符1234
。如果它有任何其他内容,包括空格、新行或空格,则会失败。通过打印出来检查x
的值,并确保它是您所期望的值。。。真的很擅长垃圾收集。。。尤其是当你打开一个文件来阅读。。。尽管如此,还是有可靠的建议
print ('Enter Password')
s = input() #goal is to input '1234'
x = open('text.txt', 'r').readline().rstrip() #text.txt contains '1234'
print("you typed", s)
print("file content is", x)
if s == x:
print("Access Granted")
else:
print("Access Denied")