2013-05-06 103 views
4

我有一个文件,当我打开它时,它会打印出一些段落。我需要将这些段落连同一个空间组合起来,形成一个大文本。如何在python中将文本文件中的所有行连接在一起?

例如,

for data in open('file.txt'): 
    print data 

有像这样的输出:

Hello my name is blah. What is your name? 
Hello your name is blah. What is my name? 

输出怎么会是这样?:

Hello my name is blah. What is your name? Hello your name is blah. What is my name? 

我试着像这样一个空间,更换新行:

for data in open('file.txt'): 
     updatedData = data.replace('\n',' ') 

但只有摆脱空行,它不会加入段落

,也试图加入,像这样:

for data in open('file.txt'): 
    joinedData = " ".join(data) 

但分隔用空格每一个字符,而不是摆脱段落格式任。

回答

9

你可以使用str.join

with open('file.txt') as f: 
    print " ".join(line.strip() for line in f) 

line.strip()将从线路两端删除所有类型的空格中。 您可以使用line.rstrip("\n")删除尾部"\n"

如果file.txt包含:

Hello my name is blah. What is your name? 
Hello your name is blah. What is my name? 

那么输出将是:

Hello my name is blah. What is your name? Hello your name is blah. What is my name? 
+0

谢谢你,这工作! – user2353608 2013-05-06 07:07:35

4

您遍历各行,它是加入新行的print声明。下面将工作:

for data in open('file.txt'): 
    print data.rstrip('\n'), 

随着后面的逗号,print不添加一个新行,和.rstrip()调用删除只是从行结尾的换行。

或者,您需要将所有读取和剥离的行传递给' '.join(),而不是每行本身。 python中的字符串是序列号,所以在行中包含的字符串在被传递到' '.join()时被解释为独立的字符。

下面的代码使用了两个新的技巧;上下文管理器和一个列表理解:

with open('file.txt') as inputfile: 
    print ' '.join([line.rstrip('\n') for line in inputfile]) 

with语句使用文件对象的上下文管理器,这意味着该文件将在我们与缩进低于with语句块中完成自动关闭。[.. for .. in ..]语法从inputfile对象中生成一个列表,我们将每行转换为最终没有换行符的版本。

+2

这里最好的答案,尤其是第一个避免将整个文件存储在内存中 – jamylak 2013-05-06 08:02:52

1
data = open('file.txt').read().replace('\n', '')