Python: Write to File

By Xah Lee. Date: . Last updated: .

Write to File

import sys

import os

xtestfile = os.path.expanduser("~/xtest.txt")

# write file, overwrite exsiting file
# if file no exist, it is created
xfile = open(xtestfile, "w", encoding="utf-8")

xfile.write("hello\n")

xfile.close()

print("done")

Append to File

import sys
import os

xtestfile = os.path.expanduser("~/xtest.txt")

# append to file
# if file no exist, it is created
xfile = open( xtestfile, "a", encoding="utf-8")

xfile.write("hello\n")

xfile.close()

print("done")

Python, Read Write File