Yohan Chevalier
Yohan Chevalier

Reputation: 73

Unexpected space inserted by readline

I'm facing an issue when I try to read and print lines from two files. These files are similar but a space is always inserted in the second line printed. Of course no one exists in my files.

file1 = open("compare1", "r")
file2 = open("compare2", "r")
while 1:
    line1 = file1.readline()
    line2 = file2.readline()
    if line1 == "" or line2 == "":
        break
    print(line1, line2)
file1.close()
file2.close()

The result is the following one :

Salut je m'appelle Yohan
 Salut je m'appelle Yohan

Je suis très content
 Je suis très content

Opening the file in a with block generates the same result.

The expected result is

Salut je m'appelle Yohan
Salut je m'appelle Yohan

Je suis très content
Je suis très content

Do you have an idea how I can fix this?

Upvotes: 0

Views: 59

Answers (1)

Wondercricket
Wondercricket

Reputation: 7882

Each line within a text file implicitly ends with a newline (\n). When you are printing out line1 and line2, it effectively becomes:

Salut je m'appelle Yohan\n Salut je m'appelle Yohan

Which outputs as

Salut je m'appelle Yohan
 Salut je m'appelle Yohan

To fix the problem just add strip to the end of your readline calls

    line1 = file1.readline().strip()
    line2 = file2.readline().strip()

    print(line1, line2, sep='\n')

    >>> Salut je m'appelle Yohan
    >>> Salut je m'appelle Yohan

Upvotes: 1

Related Questions