向文件追加文本?

12 投票
1 回答
33150 浏览
提问于 2025-04-17 13:05
  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 个回答

22

使用模式 a 而不是 w 来向文件添加内容:

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

撰写回答