Connoreel
Connoreel

Reputation: 1

Python readline() doesn't read line properly

When I have a text file and the first line is "hello", if I write

reader = open('txtfile.txt', 'r')
line = reader.readline()
print(line)

it will print "hello". Then, when I write

input = input()
if line == input:
    print('they are the same')
else:
    print('they are not the same')

it says that they are not the same, even when the input is "hello". Is this a problem with my code or does readline() not allow for this?

Upvotes: 0

Views: 1973

Answers (1)

user
user

Reputation: 5716

I suggest using with open() as.. : because...

This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

Your program would become:

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

Also, avoid naming your variable 'input' since it will shadow the name of the build-in input().


If your file is:

hello
Hi
bye

then your first line would be 'hello\n'. replace() removes that \n before the comparison.

Upvotes: 2

Related Questions