Python readline()不';我不能正确地读这行
当我有一个文本文件,第一行是“你好”,如果我写Python readline()不';我不能正确地读这行,python,Python,当我有一个文本文件,第一行是“你好”,如果我写 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') 它说它们不一样,即使输入是“hello”。这是我的代
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')
它说它们不一样,即使输入是“hello”。这是我的代码的问题还是readline()不允许这样做?我建议将
与open()一起用作..:代码>
这样做的好处是,即使在执行过程中引发异常,文件也会在其套件完成后正确关闭
您的程序将成为:
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'
<代码>替换()
删除比较之前的\n
你确定没有换行吗?您也不应该覆盖内置函数的名称,如input
。有新行,文件类似于hello
其他单词
更多单词
这会影响它读取文件的方式吗?请尝试打印len(line)
并与len(input)进行比较
*但是请注意,您应该更改变量input
的名称,这样它就不会覆盖input()
)