kaushik
kaushik

Reputation: 5969

problem with f.readline()?

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?

Upvotes: 2

Views: 894

Answers (3)

ʇsәɹoɈ
ʇsәɹoɈ

Reputation: 23479

for line in f:
    words = line.split()

Upvotes: 4

Alex Martelli
Alex Martelli

Reputation: 881665

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?!

Upvotes: 5

Mike Graham
Mike Graham

Reputation: 76683

  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.

Upvotes: 7

Related Questions