Writing Files

Using open() with "w" mode, you can create or overwrite files. The with statement ensures files are closed properly.

filename = "sample.txt"

with open(filename, "w", encoding="utf-8") as file:

file.write("Hello file handling!\n")