Python: How to continue writing on the same line in a file?

Here is a snippet:

f = open("a.txt","r")
paragraph = f.readlines()
f1 = open("o.txt","w")
for line in paragraph:
    f1.write(line)

Here, how can I manage to write continuosly on the same line in o.txt?
For example, a.txt:

Hi,   
how  
are   
you?

Then o.txt should be:

Hi, how are you?

Thanks in advance.

Answer

remove new line char using rstrip

f = open("a.txt","r")
paragraph = " ".join(map(lambda s: s.rstrip('n'), f.readlines()))
f1 = open("b.txt","w")
f1.write(paragraph)

Leave a Reply

Your email address will not be published. Required fields are marked *