Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a single line in text file using Python?
Python provides built-in capabilities for file creation, writing, and reading. You can handle both text files and binary files in Python. This article demonstrates how to write a single line to a text file using different modes.
To write to a file, first open it using the open() function, then use the write() method to save text. The file mode determines where the text will be placed ?
"w" − Write mode clears the file content and writes at the beginning
"a" − Append mode adds text at the end without clearing existing content
Syntax
file = open("filename.txt", "mode")
file.write("text content")
file.close()
Writing in Write Mode
Write mode ("w") creates a new file or overwrites existing content ?
# Open file in write mode
file = open('example.txt', 'w')
file.write("Hello, World!")
file.close()
# Read and display the content
with open('example.txt', 'r') as f:
content = f.read()
print("File content:", content)
File content: Hello, World!
Writing in Append Mode
Append mode ("a") adds text to the end of existing content without clearing it ?
# First, create a file with some content
with open('example.txt', 'w') as f:
f.write("First line\n")
# Now append new content
file = open('example.txt', 'a')
file.write("Second line")
file.close()
# Read and display all content
with open('example.txt', 'r') as f:
content = f.read()
print("File content:")
print(content)
File content: First line Second line
Using Context Manager (Recommended)
The with statement automatically handles file closing, even if errors occur ?
# Write using context manager
with open('example.txt', 'w') as file:
file.write("This is a single line written safely!")
# Read to verify
with open('example.txt', 'r') as file:
content = file.read()
print("Content:", content)
Content: This is a single line written safely!
Comparison of Methods
| Mode | Behavior | Use Case |
|---|---|---|
"w" |
Overwrites existing content | Creating new files or replacing content |
"a" |
Appends to existing content | Adding to log files or existing data |
with statement |
Auto-closes file | Recommended for safety |
Conclusion
Use "w" mode to overwrite files and "a" mode to append content. Always use the with statement for automatic file handling and better resource management.
