[英]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.