Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.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
Python:如何继续在文件中的同一行上编写?_Python_File - Fatal编程技术网

Python:如何继续在文件中的同一行上编写?

Python:如何继续在文件中的同一行上编写?,python,file,Python,File,以下是一个片段: f = open("a.txt","r") paragraph = f.readlines() f1 = open("o.txt","w") for line in paragraph: f1.write(line) 在这里,我如何在o.txt中的同一行上连续写入 例如,a.txt: Hi, how are you? 那么o.txt应该是: Hi, how are you? 提前感谢。您需要删除行,然后加入并写入文件: with open("a.t

以下是一个片段:

f = open("a.txt","r")
paragraph = f.readlines()
f1 = open("o.txt","w")
for line in paragraph:
    f1.write(line)
在这里,我如何在o.txt中的同一行上连续写入 例如,
a.txt

Hi,   
how  
are   
you?
那么
o.txt
应该是:

Hi, how are you?

提前感谢。

您需要删除行,然后加入并写入文件:

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join(in_f.read().replace('\n','')))
同时也是处理文件的一种更具python风格的方式

或者更好:

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join(map(str.strip(),in_f))
或者使用列表:

with open("a.txt","r") as in_f,open("o.txt","w") as out_f: 
    out_f.write(' '.join([line.strip() for line in in_f])

使用
rstrip

f = open("a.txt","r")
paragraph = " ".join(map(lambda s: s.rstrip('\n'), f.readlines()))
f1 = open("b.txt","w")
f1.write(paragraph)

这是因为Python读取整行,包括Python中表示为
\n
的新行字符。示例中的字符串将生成如下数组:

['Hi,\n', 'how\n', 'are\n', 'you?']
要解决此问题,您需要从每一行中删除尾随的
\n
,但请注意最后一行可能不包含
\n
,因此您不能只删除每一行的最后一个字符。python中内置了一些预先制作的方法,可以帮助您从字符串的开头和结尾删除空白字符(如新行
\n
和空格
“”

官方文档可能有点令人望而生畏,但从文档中查找和使用信息可能是计算领域最重要的技能之一。查看官方文档,看看是否在string类中找到任何有用的方法。
我找到了解决办法。来了。基本上使用
replace()


欢迎使用其他方法!:)

如果您熟悉流(例如,在C++中),这也可能很有用,它使您可以在任何地方输入结束行字符:这将仍然保留换行符
“”。join(in_f)
将保留新行char@mata是的,一个愚蠢的错误!;)<代码>映射(str.strip,f)在没有lambda和readlines的情况下执行相同的操作。但是,这会删除每行开头和结尾的所有空格。@DmitryAgibov
lambda
会降低代码的性能,正如mata所说,您可以使用
map
列表理解
,任何一种方法都是很好的尝试。
map(str.strip,f)
它的语法准确吗<代码>映射没有
lambda
?哪种python版本支持此功能?
['Hi,\n', 'how\n', 'are\n', 'you?']
f = open("a.txt","r")
paragraph = f.readlines()
f1 = open("o.txt","w")
for line in paragraph:
    line = line.replace("\n"," ")
    f1.write(line)