[英]Python readline() doesn't read line properly
当我有一个文本文件并且第一行是“你好”时,如果我写
reader = open('txtfile.txt', 'r')
line = reader.readline()
print(line)
它会打印“你好”。 然后,当我写
input = input()
if line == input:
print('they are the same')
else:
print('they are not the same')
它说它们不一样,即使输入是“你好”。 这是我的代码有问题还是 readline() 不允许这样做?
我建议使用with open() as.. :
因为...
这样做的好处是文件在其套件完成后会被正确关闭,即使在途中引发异常也是如此。
你的程序会变成:
with open('txtfile.txt', 'r') as f:
for line in f:
answer = input('\nContent?')
if line.replace('\n','') == answer:
print('they are the same')
else:
print('they are not the same')
此外,避免命名变量'input'
因为它会影响内置input()
。
如果您的文件是:
hello
Hi
bye
那么你的第一行就是'hello\\n'
。 replace()
在比较之前删除\\n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.