Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从第行读取时返回newline-Python_Python - Fatal编程技术网

从第行读取时返回newline-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

我试图编写一个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 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()
也会删除空格和制表符。。。不确定这是否是您想要的。

这是因为您正在打印的行包含新行字符