Continue writing in same line of file

2020-06-21 03:14发布

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.

3条回答
女痞
2楼-- · 2020-06-21 03:40
while loop:
for loop:
    /*do something
    */
    if some_condition:
        data.write(str(tag)+"")
data.write(" ")

In other words, remove the data.write("\n");

查看更多
姐就是有狂的资本
3楼-- · 2020-06-21 03:43

Try removing data.write("\n") .

查看更多
劳资没心,怎么记你
4楼-- · 2020-06-21 03:49

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

data.write(str(tag).rstrip('\n'))
查看更多
登录 后发表回答