Thursday, November 8, 2018

io - Append a text to file in Python





  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;

Answer



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!')

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...