Reading and Writing with CSV and JSON Files in Python
#Reading Writing with CSV and JSON Files in Python
File handling is one of the most important concepts in Python programming. It allows developers to store, access, read, and modify data in files efficiently. Whether you are working with text files, CSVs, or JSON, mastering file operations in Python is essential.
In this article, we’ll cover how to read and write files in Python with examples, modes, and best practices.
Store data permanently beyond program execution.
Process large datasets efficiently.
Read and update logs, CSV, or configuration files.
Enable communication between applications.
To open a file, Python provides the built-in open()
function:
file = open("example.txt", "r") # Opens file in read mode
"r"
→ Read (default)
"w"
→ Write (overwrites file if it exists)
"a"
→ Append (adds data to the end of file)
"x"
→ Create (new file, error if exists)
"b"
→ Binary mode (e.g., images, PDFs)
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
with open("output.txt", "w") as file:
file.write("Hello, Python File Handling!\n")
with open("output.txt", "a") as file:
file.write("Adding more content...\n")
with open("image.jpg", "rb") as file:
data = file.read()
with open("copy.jpg", "wb") as file:
file.write(data)
Python provides the csv
module for handling CSV data.
import csv
# Writing to CSV
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
writer.writerow(["Bob", 30])
# Reading from CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Python provides the json
module for handling JSON data.
import json
# Writing JSON
person = {"name": "Alice", "age": 25, "city": "New York"}
with open("data.json", "w") as file:
json.dump(person, file)
# Reading JSON
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Always use with open()
to ensure file closes automatically.
Use exception handling (try-except
) to avoid crashes.
Be careful with "w"
mode, as it overwrites existing files.
Use proper encoding (utf-8
) for text files.
Use libraries like csv
and json
for structured data handling.
Python makes file handling simple and powerful with its built-in functions. By mastering reading, writing, CSV, and JSON file handling, you can efficiently manage data, build loggers, process datasets, and create real-world applications.