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.
'w'
mode to write (overwrites existing content), 'a'
to append.write()
, writelines()
.'wb'
mode for writing binary data.with
statement for safe file handling.with open('output.txt', 'w') as file:
file.write("Hello, world!\n")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)
with open('output.txt', 'a') as file:
file.write("This line is appended.\n")
numbers = [1, 2, 3, 4]
with open('numbers.txt', 'w') as file:
for num in numbers:
file.write(str(num) + '\\n')
with open('utf8.txt', 'w', encoding='utf-8') as file:
file.write("Some UTF-8 text: café\n")
with open('binaryfile.bin', 'wb') as file:
data = bytes([120, 3, 255, 0])
file.write(data)
name = "Alice"
score = 95
with open('results.txt', 'w') as file:
file.write(f"{name} scored {score} points.\n")
try:
with open('output.txt', 'w') as file:
file.write("Safe writing example\n")
except IOError as e:
print("File write error:", e)
with open('user_input.txt', 'w') as file:
for _ in range(3):
line = input("Enter a line: ")
file.write(line + '\\n')
with open('output.txt', 'w') as file:
pass # this truncates the file, making it empty