tags:

views:

89

answers:

4

I have a file: Alus.txt

File content: (each name in new line)

Margus

Mihkel

Daniel

Mark

Juri

Victor

Marek

Nikolai

Pavel

Kalle

Problem: While programm reads this file, there are \n after each name (['Margus\n', 'Mihkel\n', 'Daniel\n', 'Mark\n', 'Juri\n', 'Victor\n', 'Marek\n', 'Nikolai\n', 'Pavel\n', 'Kalle']). How can I remove \n and have a list with names? What I am doing wrong? Thank you.

alus = []

file = open('alus.txt', 'r')

while True:

    rida = file.readline()

    if (rida == ''):

        break

    else:

        alus.append(rida)
+4  A: 

You can remove the linebreaks with rstrip:

alus = []
with open('alus.txt', 'r') as f:
    for rida in f:
        rida=rida.rstrip()
        if rida: alus.append(rida)
        else: break

By the way, the usual way to test if a string is empty is

if not rida:

rather than

if (rida == ''):

And if you have an if...else block, you should consider the non-negated form:

if rida:

since it is usually easier to read and understand.

Edit: My previous comment about removing break was wrong. (I was mistaking break with continue.) Since break stops the loop, it needs to be kept to preserve the behavior of your original code.

Edit 2: A.L. Flanagan rightly points out that rstrip removes all trailing whitespace, not just the ending newline character(s). If you'd like to remove the newline characters only, you could use A.L. Flanagan's method, or list the characters you wish to remove as an argument to rstrip:

rida = rida.rstrip(r'\r\n')
unutbu
+4  A: 
alnus = [l.rstrip() for l in open('alus.txt', 'r')]
Satoru.Logic
+1  A: 

One possible problem with rstrip() is that it will remove any whitespace. If you want to preserve whitespace, you can use slices:

if line.endswith('\n'):
    line = line[:-1]

If you could be sure all the lines end with '\n', you could speed it up by removing the if. However, in general, you can't be sure the last line in a text file has a newline.

A. L. Flanagan
"Slices" is nto a good solution here - if you have to care about gettign rid only of "\n", pass "\n" as a parameter do rstrip.
jsbueno
+2  A: 

open('alus.txt').read().splitlines()

twneale
This is my favorite.
Paul McGuire
While the response marked as the answer is correct and informative, this is the more pythonic way.
Binary Phile