Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with f.readline()?

Tags:

python

file-io

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?

like image 741
kaushik Avatar asked May 24 '26 11:05

kaushik


2 Answers

  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.

like image 125
Mike Graham Avatar answered May 26 '26 01:05

Mike Graham


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

like image 43
Alex Martelli Avatar answered May 26 '26 00:05

Alex Martelli