Thursday 8 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...