How to Write to a File in Python: Simple Guide
To write to a file in Python, use the
open() function with mode 'w' or 'a' to open the file, then call write() on the file object. Always close the file or use a with block to handle it safely.Syntax
Use open(filename, mode) to open a file. The mode can be 'w' to write (overwrite) or 'a' to append. Then use write() to add text. Finally, close the file or use with to auto-close.
python
with open('filename.txt', 'w') as file: file.write('Your text here')
Example
This example writes a greeting message to a file named greeting.txt. It uses with to open the file safely and writes a line of text.
python
with open('greeting.txt', 'w') as file: file.write('Hello, friend!\n') file.write('Welcome to Python file writing.')
Common Pitfalls
- Forgetting to close the file can cause data loss or locked files.
- Using
'w'mode overwrites existing content, so use'a'to add without deleting. - Writing non-string data without converting causes errors.
python
wrong: file = open('data.txt', 'w') file.write(str(123)) # Convert number to string file.close() right: with open('data.txt', 'a') as file: file.write(str(123)) # Convert number to string
Quick Reference
Remember these modes when writing files:
| Mode | Description |
|---|---|
| 'w' | Write mode - creates or overwrites file |
| 'a' | Append mode - adds to end of file |
| 'x' | Create mode - creates file, errors if exists |
| 'b' | Binary mode - for non-text files |
| 't' | Text mode - default for text files |
Key Takeaways
Use
with open(filename, 'w') to write and auto-close files safely.Mode
'w' overwrites files; use 'a' to add without deleting.Always write strings; convert other data types with
str().Closing files is important to save data and free resources.
Use file modes carefully to avoid accidental data loss.