簡體   English   中英

Python 文件未將文本文件行添加到變量

[英]Python File doesnt add a text file line onto a variable

我正在嘗試從文本文件中定義一個變量

    from pathlib import Path
    import linecache
    
    line1 = Path('testing.txt').read_text()
    line1A = linecache.getline("testing.txt", 1)
    answer = line1A
    print(line1A)
    
    test = input("What is 1 + 1? ")
    if test == answer:
        print("Correct")
    else:
        if answer != answer:
            print("Wrong Answer")
Txt File
    2

它永遠不會打印答案是否正確

一行通常包括行尾,即換行符\n而用戶輸入不會。 因此, test可能是'2' ,但answer將是'2\n'

為什么Path.read_text()linecache.getline(.., 1)的並發症? 要實現open()next()可以輕松完成的功能,需要大量的管道:

with open('testing.txt') as f:
    answer = next(f).strip()  # this .strip() takes off whitespace, including \n


test = input("What is 1 + 1? ")
if test == answer:
    print("Correct")
else:
    print("Wrong Answer")

順便說一下: answer != answer永遠不會是True ,所以你最好寫if False:這意味着你可以把它去掉——我認為那只是一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM