- How to check that the file exists?
- 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