Reputation: 165
I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example:
This
is
a
sample
input
Hello
World
!!
The desired output is:
This is a sample input
Hello World !!
I try this:
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 + " ",)
Upvotes: 0
Views: 137
Reputation: 7846
You can try doing it this way:
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")
Output written on file:
This is a sample input
Hello World !!
Upvotes: 1
Reputation: 2731
Do something like this:
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
will output:
This is a sample input Hello World !!
The StringIO is there only to fake the reading of a file
Upvotes: 0