将文本追加到文件中?

12
  1. 如何检查文件是否存在?
  2. 如何将文本追加到文件中?

我知道如何创建文件,但在这种情况下,它会覆盖所有数据:

import io

with open('text.txt', 'w', encoding='utf-8') as file:
    file.write('text!')

在*nix系统中,我可以做类似以下的操作:
#!/bin/sh

if [ -f text.txt ]
    #If the file exists - append text
    then echo 'text' >> text.txt; 

    #If the file doesn't exist - create it
    else echo 'text' > text.txt;  
fi;

1
open('text.txt', 'a', encoding='utf-8') - kev
1
这似乎是 Python 3.x,因为你在 open() 中使用了 encoding 参数。是吗? - Sven Marnach
我使用了搜索但找不到答案! - tomas
1个回答

22

使用模式a来追加文件,而不是用w模式:

with open('text.txt', 'a', encoding='utf-8') as file:
    file.write('Spam and eggs!')

谢谢,我找不到“-a”关键字。请告诉我如何检查文件是否存在? - tomas
1
你为什么想要检查它是否存在?如果只有在它不存在时才添加,这是没有意义的吗? - Wooble
@Wooble,只是想知道如何做。*nix的一个解决方案:if os.path.exists(filename): - tomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接