12
  1. How to check that the file exists?
  2. How to append a text to the file?

I know how to create the file, but in this case, it overwrites all data:

import io

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

In *nix I can do something like:

#!/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;
martineau
  • 119,623
  • 25
  • 170
  • 301
tomas
  • 451
  • 2
  • 5
  • 13

1 Answers1

22

Use mode a instead of w to append to the file:

with open('text.txt', 'a', encoding='utf-8') as file:
    file.write('Spam and eggs!')
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Thank, I could not find the key `-a`. Tell please, how to check that the file exists? – tomas Feb 15 '12 at 17:01
  • 1
    Why do you want to check if it exists? Are you appending to it only if it doesn't already exist, which doesn't make sense? – Wooble Feb 15 '12 at 17:18
  • @Wooble, just want to know how to do it. One of the solutions for *nix: `if os.path.exists(filename):` – tomas Feb 15 '12 at 18:10