Python makes it easy to write and append text to files using simple built-in functions. Whether you're saving user input, generating logs, or storing results, file writing is a skill every Python developer should master.
In this tutorial, we’ll explore how to write to files using write()
and append content using append()
mode. We'll use practical examples and highlight best practices for safe and efficient file handling.
1. File Modes for Writing and Appending
Mode | Description | Effect |
---|---|---|
'w' |
Write | Creates a new file or overwrites an existing one |
'a' |
Append | Adds content to the end of the file |
2. Writing to a File Using 'w'
Mode
The 'w'
mode opens the file for writing. If the file already exists, it will be overwritten. If it doesn't exist, a new file will be created.
Example 1: Writing Text
with open("notes.txt", "w") as file:
file.write("Python is powerful.\n")
file.write("File handling is easy!")
Note: The above code creates a file called notes.txt
or replaces its content if it already exists.
3. Appending to a File Using 'a'
Mode
The 'a'
mode opens the file for appending. New content is added at the end of the file without modifying existing content.
Example 2: Appending Text
with open("notes.txt", "a") as file:
file.write("\nThis line is added later.")
This will add a new line at the end of notes.txt
.
4. Writing Data in Loops
Example 3: Writing a List to a File
lines = ["Line 1", "Line 2", "Line 3"]
with open("list.txt", "w") as file:
for line in lines:
file.write(line + "\n")
5. Writing User Input to a File
Example 4: Save User Input
name = input("Enter your name: ")
with open("users.txt", "a") as file:
file.write(name + "\n")
This will add the user's name to the file without removing previous entries.
6. Best Practices for File Writing
- Use the
with
statement to ensure the file is closed automatically - Use
'w'
only when you intend to overwrite the file - Use
'a'
to preserve existing data and add new entries - Add newline characters
\n
when writing multiple lines
7. Creating a New File Safely
Use 'x'
mode to create a file and raise an error if the file already exists.
Example 5: Safe File Creation
try:
with open("unique.txt", "x") as file:
file.write("This file is created uniquely.")
except FileExistsError:
print("File already exists.")
8. Final Thoughts
Whether you're saving data for a script or logging program activity, writing and appending files in Python is essential. Use 'w'
mode to write fresh content and 'a'
to add new data safely. Stick with the with
statement for clean, error-free file management.