从文件中读取文字并在同一行上书写

时间:2017-12-08 18:59:13

标签: python python-2.7

我有一个文件,每行包含一个单词。每个句子用空行分隔。我想读取文件并在同一行写下一个句子的全部单词。例如:

This 
is 
a
sample
input

Hello
World
!!

所需的输出是:

This is a sample input
Hello World !!

我试试这个:

file = open('Words.txt', "r")
Writfile = open('Sent.txt','w')

for line in file:
    if line in ['\n']:
        Writfile.write('\n')
    else:
        Writfile.write(line + " ",)

2 个答案:

答案 0 :(得分:1)

您可以尝试这样做:

with open("infile.txt", "r") as infile:
  string = infile.read().split("\n\n")

with open("outfile.txt", "w") as outfile:
  for s in string:
    outfile.write(s.replace("\n"," ") + "\n")

写入文件的输出:

This  is  a sample input
Hello World !!

答案 1 :(得分:0)

做这样的事情:

input = """This
is
a
sample
input

Hello
World
!!
"""

import StringIO
fi = StringIO.StringIO(input)
lines = fi.read().split("\n")
one_line = " ".join(lines)
print one_line

将输出:

This is a sample input Hello World !!

StringIO只是伪造文件的读取