Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readlines gives me additional linebreaks python2.6.5

I have problems with the following code:

file = open("file.txt", "r")
lines = file.readlines()
print lines[0]
print lines[1]
print lines[2]
file.close()

This code gives me linebreaks between the lines. So the output is something like this:

line0

line1

line2

How can this be solved?

like image 711
xamiax Avatar asked Feb 03 '26 03:02

xamiax


1 Answers

print adds a newline. Strip the newline from the line:

print lines[0].rstrip('\n')
print lines[1].rstrip('\n')
print lines[2].rstrip('\n')

If you are reading the whole file into a list anyway, an alternative would be to use str.splitlines():

lines = file.read().splitlines()

which by default removes the newlines from the lines at the same time.

like image 123
Martijn Pieters Avatar answered Feb 05 '26 16:02

Martijn Pieters