Unlike print(), write() does not add a trailing newline automatically — if you want each write() call to start a new line, you need to include a newline character explicitly in the string. write() requires the file to be opened in a writable mode, and writing to a file opened in text mode requires a str argument, while a file opened in binary mode requires a bytes argument instead — mixing the two raises a TypeError. Writes may be buffered in memory rather than immediately hitting disk, until the file is closed or explicitly flushed.
1Understanding write()
Unlike print(), write() does not add a trailing newline automatically — if you want each write() call to start a new line, you need to include a newline character explicitly in the string. write() requires the file to be opened in a writable mode, and writing to a file opened in text mode requires a str argument, while a file opened in binary mode requires a bytes argument instead — mixing the two raises a TypeError. Writes may be buffered in memory rather than immediately hitting disk, until the file is closed or explicitly flushed.
Remember write() doesn't add a newline like print() does — if you're writing multiple lines in a loop, append a newline character to each string yourself, or your output will run together on one line.
with open("output.txt", "w") as f:
f.write("Hello")
f.write(", World!")
with open("output.txt", "r") as f:
print(f.read())2Practical Example
Here is a real-world application of write() showing how it is used in production Python code.
lines = ["apple", "banana", "cherry"]
with open("fruits.txt", "w") as f:
for fruit in lines:
f.write(fruit + "\n")
with open("fruits.txt", "r") as f:
print(f.read())3Best Practices
Follow these guidelines when working with write():
1. Add a newline character explicitly to strings passed to write() when each one should start a new line
2. Use a with block so writes are properly flushed and the file is closed automatically when you're done, rather than relying on manual flush()/close() calls
3. Match the file's mode to your data: text mode with str for write(), binary mode with bytes
Tip: Remember write() doesn't add a newline like print() does — if you're writing multiple lines in a loop, append a newline character to each string yourself, or your output will run together on one line.
with open("output.txt", "w") as f:
f.write("Hello")
f.write(", World!")
with open("output.txt", "r") as f:
print(f.read())