open and append to file python if exists if not create code example
Example 1: python create file if not exists
import os
if not os.path.exists(path):
with open(path, 'w'):
Example 2: open and append to file python if exists if not create
import os
filename="file.txt"
answ=os.path.exists(filename)
with open(filename, "a" if answ else "w") as f:
if(answ):
f.write("\n")
f.write("hi!")