Reading from and writing to text and CSV files is one of the most common tasks in data processing and automation. Python makes file handling seamless with built-in methods for working with .txt
files and the powerful csv
module for .csv
files.
In this guide, you'll learn how to open, read, write, and manipulate text and CSV files using Python efficiently and safely.
1. Working with .txt
Files
Reading from a .txt File
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to a .txt File
with open("example.txt", "w") as file:
file.write("This is the first line.\n")
file.write("This is the second line.")
Appending to a .txt File
with open("example.txt", "a") as file:
file.write("\nThis line is appended.")
Reading Line-by-Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
2. Working with .csv
Files Using the csv
Module
Python’s csv
module provides functionality to read and write CSV (Comma-Separated Values) files in a clean and structured way.
Import the Module
import csv
Writing to a CSV File
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 30, "New York"])
writer.writerow(["Bob", 25, "London"])
This creates a file data.csv
with column headers and rows of data.
Appending to a CSV File
with open("data.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Charlie", 22, "Paris"])
Reading from a CSV File
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Reading as Dictionary
DictReader
reads each row as a dictionary with column headers as keys.
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["Name"], row["City"])
Writing with Dictionary
with open("employees.csv", "w", newline="") as file:
fieldnames = ["ID", "Name", "Department"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"ID": 101, "Name": "John", "Department": "Sales"})
writer.writerow({"ID": 102, "Name": "Daisy", "Department": "HR"})
3. Best Practices
- Always use
with
statement to handle file closing automatically. - Use
newline=""
while writing CSVs to avoid blank lines on Windows. - Use
csv.DictReader
andDictWriter
for cleaner, header-based access. - Handle file not found or permission errors using
try-except
.
4. Summary Table
File Type | Read | Write | Append |
---|---|---|---|
.txt | open("file.txt", "r") |
open("file.txt", "w") |
open("file.txt", "a") |
.csv | csv.reader() |
csv.writer() |
csv.writer() with "a" mode |
5. Final Thoughts
Python provides a clean and consistent approach to handling both text and CSV files. Whether you’re managing logs, storing structured data, or importing datasets, mastering .txt
and .csv
file operations is essential for everyday Python development.