向文件追加文本?
- 如何检查文件是否存在?
- 如何在文件中添加文本?
我知道怎么创建文件,但这样做会把所有数据覆盖掉:
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 个回答
22
使用模式 a
而不是 w
来向文件添加内容:
with open('text.txt', 'a', encoding='utf-8') as file:
file.write('Spam and eggs!')