从第行读取时返回newline-Python
我试图编写一个python脚本,通过读取文件生成一些代码。然而,它并没有像预期的那样工作 代码:从第行读取时返回newline-Python,python,Python,我试图编写一个python脚本,通过读取文件生成一些代码。然而,它并没有像预期的那样工作 代码: with open('continent.txt') as fp: for line in fp: print "text ", line ," here" 结果 $python.py text North America here text South America here text Central America 渴望的 text North Americ
with open('continent.txt') as fp:
for line in fp:
print "text ", line ," here"
结果
$python.py
text North America
here
text South America
here
text Central America
渴望的
text North America here
text South America here
text Central America here
尝试:
关于脱衣舞的更多信息你的问题似乎相当于一个问题 总结上述线程,您可以使用
打印“text”、line.rstrip(“\n”)、“here”
。line.rstrip(“\n”)将返回并删除字符串行中包含的任何“\n”
with open('continent.txt') as fp:
for line in fp:
print "text ", line.strip('\r\n') ," here"
也可以对fp.splitlines()中的行使用
。splitlines()返回不带换行符的行列表。就我个人而言,我是splitlines的粉丝。如果你愿意,你可以做类似的事情
lines=fp.splitlines()
对于行中的行:
[代码在这里]
调用行上的方法
with open('continent.txt') as fp:
for line in fp:
print "text ", line.strip('\r\n') ," here"
注意strip的参数指定要删除的字符。默认情况下,.strip()
也会删除空格和制表符。。。不确定这是否是您想要的。这是因为您正在打印的行包含新行字符