tags:

views:

77

answers:

3

I am reading one line at a time from a file, but at the end of each line it adds a '\n'.

Example:
The file has: 094 234 hii
but my input is: 094 234 hii\n

I want to read line by line but I don't need to keep the newlines...

My goal is to read a list from every line: I need ['094','234','hii'], not ['094','234','hii\n'].

Any advice?

+7  A: 
  1. It's not that it adds a '\n' so much as that there's really one there. Use line = line.rstrip() to get the line sans newline (or something similar to it depending on exactly what you need).

  2. Don't use the readline method for reading a file line by line. Just use for line in f:. Files already iterate over their lines.

Mike Graham
+5  A: 

The \n is not added, it's part of the line that's being read. And when you do line.split() the traiing \n goes away anyway, so why are you worrying about it?!

Alex Martelli
+4  A: 
for line in f:
    words = line.split()
Forest