readlines gives me additional linebreaks python2.6.5

前端 未结 3 417
粉色の甜心
粉色の甜心 2021-01-21 08:33

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()
         


        
3条回答
  •  -上瘾入骨i
    2021-01-21 09:14

    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()

提交回复
热议问题