Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue writing in same line of file

Tags:

python

file-io

I have opened the file I want to write to using:

data = open('input','a')

using a loop, I want to write some words to the file in the same line. And after every loop iteration I want to add a newline character.

while loop:
    for loop:
        /* do something */
        if some_condition:
            data.write(str(tag)+"")
    data.write("\n")

My expected output was:

city mountain sky sun
bay lake sun tree

But I'm getting:

city 
mountain 
sky 
sun

bay 
lake 
sun 
tree

How can I change my code to get the expected output? Thanks.

like image 969
nish Avatar asked Jun 25 '13 06:06

nish


1 Answers

Remove the newline at the end of tag before writing it.

data.write(str(tag).rstrip('\n'))
like image 101
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 23:09

Ignacio Vazquez-Abrams