如何在python的文本文件中将所有行连接在一起?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16393466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:29:02  来源:igfitidea点击:

How to join all the lines together in a text file in python?

python

提问by user2353608

I have a file and when I open it, it prints out some paragraphs. I need to join these paragraphs together with a space to form one big body of text.

我有一个文件,当我打开它时,它会打印出一些段落。我需要将这些段落与一个空格连接在一起以形成一个大正文。

for e.g.

例如

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

has an output like this:

有这样的输出:

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

How can the output be like this?:

输出怎么会是这样?:

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

I've tried replacing the newlines with a space like so:

我试过用这样的空格替换换行符:

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

but that only gets rid of the empty lines, it doesn't join the paragraphs

但这只会去除空行,不会加入段落

and also tried joining like so:

并尝试像这样加入:

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

but that separates each character with a space, while not getting rid of the paragraph format either.

但这用空格分隔每个字符,同时也没有摆脱段落格式。

采纳答案by Ashwini Chaudhary

You could use str.join:

你可以使用str.join

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

line.strip()will remove all types of whitespaces from both ends of the line. You can use line.rstrip("\n")to remove only the trailing "\n".

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

If file.txtcontains:

如果file.txt包含:

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

Then the output would be:

那么输出将是:

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

回答by Martijn Pieters

You are looping over individual lines and it is the printstatement that is adding newlines. The following would work:

您正在遍历各个行,并且print是添加换行符的语句。以下将起作用:

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

With the trailing comma, printdoesn't add a newline, and the .rstrip()call removes justthe trailing newline from the line.

使用尾随逗号,print不添加换行符,并且.rstrip()调用仅从行中删除尾随换行符。

Alternatively, you need to pass all read and stripped lines to ' '.join(), not each line itself. Strings in python are sequences to, so the string contained in line is interpreted as separate characters when passed on it's own to ' '.join().

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

The following code uses two new tricks; context managers and a list comprehension:

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

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

The withstatement uses the file object as a context manager, meaning the file will be automatically closed when we are done with the block indented below the withstatement. The [.. for .. in ..]syntax generates a list from the inputfileobject where we turn each line into a version without a newline at the end.

with语句使用文件对象作为上下文管理器,这意味着当我们完成该with语句下方缩进的块时,该文件将自动关闭。的[.. for .. in ..]语法产生从一个列表中inputfile,我们将每个线到版本,而不在端部具有换行对象。

回答by John La Rooy

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