How to Write in a Text File using Python
Writing to a text file in Python is straightforward. Python provides built-in functions to handle files using the open() function.
1. Opening a File in Python
Python provides the open() function to work with files. The syntax is:
file = open("filename.txt", mode)
"filename.txt": This is the name of the file you want to open.mode: This tells Python how to open the file (read, write, append, etc.).
Common File Modes
| Mode | Description |
|---|---|
"w" | Write mode – Creates a new file or overwrites an existing file. |
"a" | Append mode – Adds new content to an existing file. |
"x" | Exclusive mode – Creates a new file but fails if it already exists. |
"wb" | Write binary mode (used for non-text files like images, audio, etc.). |
"ab" | Append binary mode. |
2. Writing to a File
After opening a file, you can write to it using .write() or .writelines().
Method 1: Writing a Single Line Using write()
The write() function writes a single string to the file.
Example:
file = open("example.txt", "w") # Open file in write mode
file.write("Hello, this is a test file.") # Writing to the file
file.close() # Closing the file
Output in example.txt:
Hello, this is a test file.
Explanation
"w"mode creates the file if it does not exist.- If the file already exists, it overwrites the content.
close()is used to save and release the file.
Method 2: Writing Multiple Lines Using writelines()
If you want to write multiple lines at once, use writelines(). This method requires a list of strings.
Example:
lines = ["Hello, world!\n", "Python file handling is easy.\n", "Goodbye!\n"]
file = open("example.txt", "w") # Open in write mode
file.writelines(lines) # Writing multiple lines
file.close()
Output in example.txt:
Hello, world!
Python file handling is easy.
Goodbye!
Explanation:
- Each string in the list is written in order.
\nis used to ensure each sentence appears on a new line.
3. Appending Data to a File
If you don’t want to overwrite existing content but instead add new text, use "a" mode.
Example:
file = open("example.txt", "a") # Open file in append mode
file.write("This is an additional line.\n") # Appends a new line
file.close()
New Output in example.txt:
Hello, world!
Python file handling is easy.
Goodbye!
This is an additional line.
Explanation:
"a"mode does not erase existing content.- It appends new text to the end of the file.
4. Using with open() (Best Practice)
Using the with statement ensures that the file is automatically closed after use.
Example:
with open("example.txt", "w") as file:
file.write("This is a better way to write files in Python.")
Output in example.txt:
This is a better way to write files in Python.
Why use with open()?
- The file closes automatically, even if an error occurs.
- It’s cleaner and safer than manually calling
close().
5. Writing with print()
You can also use print() to write to a file by specifying the file parameter.
Example:
with open("example.txt", "w") as file:
print("Hello, this is written using print().", file=file)
Output in example.txt:
Hello, this is written using print().
Explanation
print()automatically adds a newline at the end.
6. Handling Errors Using try-except
Sometimes, writing to a file may fail due to permission issues or incorrect file paths. You can handle such errors using try-except.
Example:
try:
with open("example.txt", "w") as file:
file.write("Handling errors properly!")
except IOError:
print("An error occurred while writing to the file.")
Possible Outputs
If successful:
No error, file is written.
If an error occurs (e.g., permission issues):
An error occurred while writing to the file.
Why Use Error Handling?
- Prevents program crashes.
- Helps debug issues with file paths or permissions.
7. Writing Binary Data (wb Mode)
If you’re working with binary data (e.g., images, videos, audio), use "wb" mode.
Example:
binary_data = b"Hello in binary!"
with open("binaryfile.bin", "wb") as file:
file.write(binary_data)
Explanation:
"wb"writes raw binary data.- Useful for non-text files (images, music, etc.).
8. Checking If Writing Was Successful
You can confirm writing by reading the file afterward.
Example:
with open("example.txt", "w") as file:
file.write("Testing file writing.")
# Reading the file to verify
with open("example.txt", "r") as file:
print(file.read()) # Output will be printed
Output in Console:
Testing file writing.
9. Summary Table
| Mode | Description |
|---|---|
"w" | Overwrites file (creates if it doesn’t exist). |
"a" | Appends to existing file. |
"x" | Creates a new file, but errors if it exists. |
"wb" | Write binary data. |
"ab" | Append binary data. |
Final Thoughts
- Use
"w"mode only when you need to overwrite content. - Use
"a"mode if you want to add new content without deleting existing data. - Always close the file after writing (or use
with open()). - Use
"wb"if dealing with binary files like images or audio. - Handle errors properly with
try-except.