Python:写入文件

时间:2012-11-16 07:54:36

标签: python

我一直遇到这个问题。如何在python中打开文件并继续写入文件但不覆盖之前写的文件?

例如:

下面的代码会写'输出正常'。 然后接下来的几行将覆盖它,它将只是'DONE'

但我想要两个 '输出还可以' “完成” 在文件中

f = open('out.log', 'w+')
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
f.close()
# some other work
f = open('out.log', 'w+')
f.write('done\n')
f.flush()
f.close()

我希望能够在一定时间内自由地打开和写入它。关闭它。然后一遍又一遍地重复这个过程。

感谢您的帮助:D

5 个答案:

答案 0 :(得分:11)

以追加模式打开文件。如果它不存在,它将被创建,如果它存在,它将在其末尾打开以进一步写入:

with open('out.log', 'a') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')

# some other work
with open('out.log', 'a') as f:
    f.write('done\n')

答案 1 :(得分:2)

当您打开文件以在其中附加内容时,只需将'a'作为参数传递。请参阅doc

f = open('out.log', 'a')

答案 2 :(得分:2)

您需要第二次以追加模式打开文件:

f = open('out.log', 'a')

因为每次在写入模式下打开文件时,文件的内容都会被删除。

答案 3 :(得分:2)

在第一次写作之后,您需要使用f = open('out.log', 'a') 追加将文本添加到文件内容中。

答案 4 :(得分:2)

with open("test.txt", "a") as myfile:
    myfile.write("appended text")