Search code examples
pythonlistline-endings

Stripping line edings before appending to a list?


Ok I am writing a program that reads text files and goes through the different lines, the problem that I have encountered however is line endings (\n). My aim is to read the text file line by line and write it to a list and remove the line endings before it is appended to the list.

I have tried this:

thelist = []    
inputfile = open('text.txt','rU')    

for line in inputfile:
    line.rstrip()
    thelist.append(line)

Solution

  • rstrip doesn't change its argument, it returns modified string, that's why you must write it so:

    thelist.append(line.rstrip())
    

    But you can write your code simpler:

    with open('text.txt', 'rU') as inputfile:
        thelist = [x.rstrip() for x in inputfile]