继续在文件的同一行中写入 [英] Continue writing in same line of file

查看:70
本文介绍了继续在文件的同一行中写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已打开要使用的文件:

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")

我的预期输出是:

city mountain sky sun
bay lake sun tree

但是我得到了:

city 
mountain 
sky 
sun

bay 
lake 
sun 
tree

如何更改代码以获得预期的输出?谢谢.

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

推荐答案

在编写tag末尾之前删除换行符.

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

data.write(str(tag).rstrip('\n'))

这篇关于继续在文件的同一行中写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆