Reputation: 5969
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
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
Reputation: 76683
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).
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