readlines gives me additional linebreaks python2.6.5

梦想与她 提交于 2019-12-01 23:39:03

问题


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?


回答1:


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.




回答2:


Do strip after each line. File has new line as last character. You have to remove it when you read it.

print line[index].strip()



回答3:


readlines() will return an array of lines. Every line ends up with a line break.

If you want to print all lines in a block, simply do this:

with open("file.txt", "r") as file:
    lines = file.readlines()
    print "".join(lines)

Use with, you can ever save a file.close()



来源:https://stackoverflow.com/questions/22302868/readlines-gives-me-additional-linebreaks-python2-6-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!