✍️

How to Write Files in Python

PythonBeginner

Write and append content to text files.

Code Example

Python
# Write to file (creates or overwrites)
with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")
    f.write("Third line\n")

print("File created: output.txt")

# Append to file
with open("output.txt", "a") as f:
    f.write("Appended line 1\n")
    f.write("Appended line 2\n")

print("Lines appended")

# Write multiple lines at once
lines = ["Line A\n", "Line B\n", "Line C\n"]
with open("batch.txt", "w") as f:
    f.writelines(lines)

print("Batch file created: batch.txt")

# Read back to verify
with open("output.txt", "r") as f:
    print("\nContent of output.txt:")
    print(f.read())

Explanation

Use "w" mode to write (overwrites), "a" mode to append. Use write() for single strings, writelines() for lists of strings.

Related Tutorials