简体   繁体   中英

Python File doesnt add a text file line onto a variable

I am trying to make a define a variable from a text file

    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

It's never printing the if the answer is right or not

A line typically includes a line ending, ie a newline character \n and the user input won't. So, test might be '2' , but answer will be '2\n' .

Why the complications with Path.read_text() and linecache.getline(.., 1) ? That's a lot of plumbing to achieve what open() and next() could do just as easily:

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")

By the way: answer != answer will never be True , so you might as well write if False: which means you can just leave it out - I assume that was just a mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM