Working with Text Files in Python (Read, Write, Append)
What Is a Text File in Python?
A text file is a file that contains plain text data (usually ending with .txt). Python provides built-in support to read, write, append, and process text files efficiently using the open() function.
Common File Modes for Text Files
Mode | Meaning |
---|---|
'r' | Read (default) |
'w' | Write (overwrites) |
'a' | Append |
'r+' | Read and write |
'w+' | Write and read (overwrite) |
'a+' | Append and read |
Reading from a Text File
Example 1: read() - Read Entire File
with open('notes.txt', 'r') as file:
data = file.read()
print(data)
Example 2: readline() - Read One Line
with open('notes.txt', 'r') as file:
line1 = file.readline()
line2 = file.readline()
print(line1.strip())
print(line2.strip())
Example 3: readlines() - Read All Lines as List
with open('notes.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Writing to a Text File
Example: Overwrite with write()
with open('notes.txt', 'w') as file:
file.write("Python is powerful.\n")
file.write("File handling is easy!")
File Content:
Python is powerful. File handling is easy!
Warning: 'w' mode will delete the existing content.
Appending to a Text File
Example:
with open('notes.txt', 'a') as file:
file.write("\nThis is an appended line.")
Updated Content:
Python is powerful. File handling is easy! This is an appended line.
Read and Write in the Same File
with open('notes.txt', 'r+') as file:
content = file.read()
file.write("\n-- Updated at the end --")
Pro Tips for Working with Text Files
- Always use with open() to auto-close files safely.
- Use .strip() or .rstrip() to remove \n while reading.
- Prefer try-except blocks for error handling.
Bonus: Count Words in a Text File
with open('notes.txt', 'r') as file:
words = file.read().split()
print("Total words:", len(words))
Example Project Folder Structure
project/ │ ├── notes.txt ├── read_notes.py ├── write_notes.py