To read and write files safely in Python, always use the
withstatement alongside the built-inopen()function and explicitly specify theencoding="utf-8"parameter.Using
withautomatically closes the file even if an error interrupts your program, preventing memory leaks and file corruption.Use
"r"for reading,"w"to overwrite or create a new file,"a"to append to the end without erasing existing data, and"x"to create a file only if it does not already exist.
# Writing safely to a file
with open("example.txt", mode="w", encoding="utf-8") as file:
file.write("First line of text.\n")
file.write("Second line of text.\n")
# Reading safely from a file
try:
with open("example.txt", mode="r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")