Writing Files in Python

Writing data to files is a core operation for data persistence, logging, and data export. Python offers simple and flexible methods to write text or binary data to files.

Key Concepts

10 Python Examples for Writing Files

Example 1: Writing a string to a file

with open('output.txt', 'w') as file:
    file.write("Hello, world!\n")

Example 2: Writing multiple lines using writelines()

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
    file.writelines(lines)

Example 3: Appending text to an existing file

with open('output.txt', 'a') as file:
    file.write("This line is appended.\n")

Example 4: Writing numbers as strings

numbers = [1, 2, 3, 4]
with open('numbers.txt', 'w') as file:
    for num in numbers:
        file.write(str(num) + '\\n')

Example 5: Writing with encoding specified

with open('utf8.txt', 'w', encoding='utf-8') as file:
    file.write("Some UTF-8 text: café\n")

Example 6: Writing binary data

with open('binaryfile.bin', 'wb') as file:
    data = bytes([120, 3, 255, 0])
    file.write(data)

Example 7: Writing formatted data using f-strings

name = "Alice"
score = 95
with open('results.txt', 'w') as file:
    file.write(f"{name} scored {score} points.\n")

Example 8: Using try-except with file writing

try:
    with open('output.txt', 'w') as file:
        file.write("Safe writing example\n")
except IOError as e:
    print("File write error:", e)

Example 9: Writing lines from user input

with open('user_input.txt', 'w') as file:
    for _ in range(3):
        line = input("Enter a line: ")
        file.write(line + '\\n')

Example 10: Overwriting a file with empty content

with open('output.txt', 'w') as file:
    pass  # this truncates the file, making it empty