简体   繁体   English

Python 文件未将文本文件行添加到变量

[英]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.一行通常包括行尾,即换行符\n而用户输入不会。 So, test might be '2' , but answer will be '2\n' .因此, test可能是'2' ,但answer将是'2\n'

Why the complications with Path.read_text() and linecache.getline(.., 1) ?为什么Path.read_text()linecache.getline(.., 1)的并发症? That's a lot of plumbing to achieve what open() and next() could do just as easily:要实现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")

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.顺便说一下: answer != answer永远不会是True ,所以你最好写if False:这意味着你可以把它去掉——我认为那只是一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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