Python的print语句在使用逗号时会打印一个换行符

3

'2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3]'

我有这个版本

#! /usr/bin/env python

f = open('filetest', 'w')
f.write("This is a line")

f.close()

f = open('filetest', 'r')


for i in f.readlines():
    print i,

这将打印输出如下:
$ ./filetest.py 
This is a line
abc@abc-ubuntu:~/pythonpractice$

我想知道为什么在打印“This is a line”后会换行? 因为运行cat filestest会得到以下结果:

$ cat filetest
This is a lineabc@abc-ubuntu:~/pythonpractice$ 
3个回答

4

1

或者您也可以使用:

#! /usr/bin/env python
from __future__ import print_function

with open('filetest', 'w') as f1:
    f1.write("This is a line")

with open('filetest', 'r') as f2:
    for line in f2.readlines():
        print(line, end='')

1
尝试在处理文件时始终使用“with”关键字,这样更加规范。 - DevLounge

1
from __future__ import print_function

for line in f:
    print(line, end="")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接