Phil
Phil

Reputation: 11

Printing from a file using readlines - new lines are doubled

My code is

def print_words():
    letter=input("Enter First Letter:\n")
    file=open("english.txt", "r")
    words=[]
    for word in file.readlines():
        words.append(word)
        if word[0].lower()==letter.lower():
            print(word)

print_words()

My output has an empty line after every line that it prints for some reason. Any advice?

Upvotes: 1

Views: 433

Answers (2)

cglacet
cglacet

Reputation: 10912

When you have that kind of issues, the best way to understand it is to print visible characters around your output:

def print_words():
    letter=input("Enter First Letter:\n")
    file=open("english.txt", "r")
    words=[]
    for word in file.readlines():
        words.append(word)
        if word[0].lower()==letter.lower():
            print("-", word, "-")

print_words()

By doing so you can already have a vague idea of the origin of the problem, after entering a j:

- je suis là
 -
- je sais
 -

As suggested you could even use print(repr(word)) which would instead output:

'je suis là\n'
'je sais \n'

The word contains the whole line, including the end of line. A quick fix would be to print without including a new line print(word, end="").

Upvotes: 0

Matias Cicero
Matias Cicero

Reputation: 26281

file.readlines returns an array with all the lines, however it does not remove the trailing new line character (e.g. ['hello\n', 'bye\n']).

When you print them, it's printing out the embedded new line character plus another new line inserted by print itself.

There are two ways to simply fix this:

  1. Tell print not to insert a new line:
print(word, end='')
  1. Remove the trailing \n from each word:
word = word.strip()
# Or, if you want to be extremely specific: word = word.strip('\n')

Upvotes: 4

Related Questions