在Python中将文本附加到文件

tom*_*mas 7 python io

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

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

import io

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

*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;
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 18

使用模式a而不是w附加到文件:

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