Add text to file in Python

  • How to check if a file exists?
  • How to add text to a file?

I know how to create a file, but in this case it overwrites all the 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; 
+6
source share
2 answers

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

 with open('text.txt', 'a', encoding='utf-8') as file: file.write('Spam and eggs!') 
+15
source

As for your first question, there will be several ways to search on Google. Try this earlier SO question:

Pythonic way to check if a file exists?

0
source

Source: https://habr.com/ru/post/908535/


All Articles