【问题标题】:python append to new line in filepython追加到文件中的新行
【发布时间】:2016-11-29 20:49:26
【问题描述】:

我正在尝试将文本附加到 python 中的新行,但它一直将其直接添加到最后一句话结束的同一行。我尝试添加 '\n' 但它会产生两个空行。例如;

text = 'hello there'

with open('hello.txt', 'ab') as temp_file:
    temp_file.write('\n' + text)

如果我运行上述 3 次,我会得到;

# empty line
# empty line      
hello there
hello there
hello there

有没有办法将文本附加到下一个新行,而不留下任何空行?我知道我可以编写另一个 with open 函数来去除空行,但想看看是否有更清洁、更紧凑的方法。谢谢。

【问题讨论】:

  • 你用的是windows吗?以及您使用哪个编辑器来查看结果?
  • 您是否尝试过在text 之后添加换行符,例如temp_file.write(text + '\n')?这与print 函数/语句的行为最相似。
  • 这是一个 python 2 的问题,在 python 3 中不起作用。我只有 1 个空行,然后是文本,正如预期的那样。你到底想达到什么目的?例如,在 3 次调用之后,您期望的输出是什么?
  • @Jean-FrançoisFabre 我正在使用 Linux (centos 7.2) 并使用 vim 作为我的编辑器。我也在使用 python 2.7
  • @BrianCain 我试过了,但这次它在顶部增加了一行。

标签: python python-2.7 file line


【解决方案1】:
import subprocess
subprocess.check_output('echo "' + YOURTEXT + '" >> hello.txt',shell=True)

万无一失

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2021-09-04
    • 2015-08-12
    相关资源
    最近更新 更多