0

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 + " ",)
user3001418
  • 155
  • 1
  • 3
  • 14
  • possible double with https://stackoverflow.com/questions/23598410/python-read-a-line-and-write-back-to-that-same-line ? – Ivonet Dec 08 '17 at 19:03
  • Possible duplicate of [Python: read a line and write back to that same line](https://stackoverflow.com/questions/23598410/python-read-a-line-and-write-back-to-that-same-line) – CodeLikeBeaker Dec 08 '17 at 19:04
  • Also, please be more specific about the errors you are encountering with your attempted approach. – Michael Ohlrogge Dec 08 '17 at 20:26
  • @MichaelOhlrogge, Simply, I did not get the desired format, I'm not sure what you are looking for by your comment!! – user3001418 Dec 08 '17 at 21:13

2 Answers2

1

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 !!
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

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

Ivonet
  • 2,492
  • 2
  • 15
  • 28