file.readlines leaving blank lines
file.readlines()
(and also file.readline()
) includes the newlines.
Do
print i.replace('\n', '')
if you don't want them.
It may seem weird to include the newline at the end of the line, but this allows, for example, you to tell whether the last line has a newline character or not. That case in tricky in many languages' I/O.
file.readlines()
return list of strings. Each string contain trailing newlines. print
statement prints the passed parameter with newlnie.; That's why you got extra lines.
To remove extra newline, use str.rstrip
:
print i.rstrip('\n')
or use sys.stdout.write
sys.stdout.write(i)
BTW, don't use file.readlines
unless you need all lines at once. Just iterate the file.
with open("test.txt") as f:
for i in f:
print i.rstrip('\n')
...
UPDATE
In Python 3, to prevent print
prints trailing newline, you can use print(i, end='')
.
In Python 2, you can use same feature if you do : from __future__ import print_function
Answer to UPDATE
Tabs, Newlines are also considers as whitespaces.
>> ' \r\n\t\v'.isspace()
True