-1

Every time I read a text file using the following code in Python, each line (except the last) ends with the \n delimiter.

lines = open('the_file.txt').readlines()

Then, I'm forced to fix this using the following method:

for i in range(len(lines)):
    lines[i] = lines[i].replace('\n', '')

Is there a cleaner way to do this so that I don't have to use this hacky fix just to get rid of all of the \n instances?

Ryan
  • 7,621
  • 5
  • 18
  • 31

1 Answers1

1

Use a list comprehension:

lines = open('the_file.txt').readlines()
lines = [line.strip() for line in lines]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70