Write to File in Python

To write to a file in Python, no external libraries are needed. You can create, write to, and append to files using Python's built-in open() function.

Writing to a file

To write text to a file, open the file with the 'w' mode. This creates the file if it does not exist, or overwrites it if it already exists:

filename = "output.txt"

# Open file for writing
myfile = open(filename, "w")

# Write text to file
myfile.write("Written with Python\n")

# Always close the file when done
myfile.close()

Appending to a file

If you want to add text to the end of an existing file without deleting its previous contents, use the append mode 'a':

filename = "output.txt"

# Open file for appending
myfile = open(filename, "a")

# Append a new line
myfile.write("Appending a new line\n")

myfile.close()

Using the with statement

The recommended best practice in modern Python is using the with statement (context manager). This automatically closes the file when the block finishes, even if an error occurs:

with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")
Back ⚡ Practice with PyChallengeNext