Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python readline()不';我不能正确地读这行_Python - Fatal编程技术网

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