Writing Files
Writing to Files
Writing to files allows you to save data permanently. Python provides methods to write strings, lines, and formatted data to files. Understanding file writing is essential for creating programs that persist data.
You can write to files using write mode (overwrites) or append mode (adds to end), depending on your needs.
Writing Strings
The write() method writes a string to the file:
write_strings.py
# Write mode (overwrites existing file)
with open("output.txt", "w") as file:
file.write("Hello, World!")
file.write("
This is a new line")
# Append mode (adds to end of file)
with open("output.txt", "a") as file:
file.write("
This line is appended")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open("output.txt", "w") as file:
for line in lines:
file.write(line + "
")
Writing Lines
The writelines() method writes a list of strings to the file:
write_lines.py
# Using writelines()
lines = ["First line
", "Second line
", "Third line
"]
with open("output.txt", "w") as file:
file.writelines(lines)
# Write formatted data
data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
with open("data.txt", "w") as file:
for person in data:
file.write(f"{person['name']}, {person['age']}
")
Write vs Append Mode
Understanding the difference between write and append modes is crucial:
write_vs_append.py
# Write mode - overwrites file
with open("log.txt", "w") as file:
file.write("First entry
")
# File now contains: "First entry"
with open("log.txt", "w") as file:
file.write("Second entry
")
# File now contains: "Second entry" (first entry is gone!)
# Append mode - adds to file
with open("log.txt", "a") as file:
file.write("Third entry
")
# File now contains: "Second entry
Third entry"
Best Practices
✅ Writing Files Tips
• Use write mode ("w") to create new files or overwrite
• Use append mode ("a") to add to existing files
• Always add
for new lines when needed
• Be careful with write mode - it deletes existing content!
• Use formatted strings for structured data
main.py
📤 Output
Click "Run" to execute...