Learn Python File Handling: Read, Write, and Work with JSON
Master Python file handling to read, write, and manipulate data. Learn file modes, reading/writing methods, and working with JSON using the json module.
Objective:
Work with files to read and write data efficiently, including text files and JSON files, enabling Python programs to persist and process data.
Topics and Examples:
1. File Modes: r, w, a, rb, wb
Python file modes determine how a file is opened:
r– Read (default)w– Write (overwrite existing or create new)a– Append (write at the end)rb– Read binarywb– Write binary
Example:
# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello Python!\n")
file.close()
2. Reading Files: read(), readline(), readlines()
read()– Reads the entire filereadline()– Reads one line at a timereadlines()– Reads all lines into a list
Example:
# Writing sample data first
with open("example.txt", "w") as f:
f.write("Line 1\nLine 2\nLine 3\n")
# Reading file
with open("example.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("example.txt", "r") as f:
line = f.readline()
print(line)
# Reading all lines into a list
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
3. Writing Files: write() and writelines()
write()– Writes a string to the filewritelines()– Writes a list of strings
Example:
lines = ["Python\n", "File Handling\n", "Tutorial\n"]
# Writing multiple lines
with open("example.txt", "w") as f:
f.writelines(lines)
# Writing a single line
with open("example.txt", "a") as f:
f.write("Appended Line\n")
4. Working with JSON: json Module
JSON (JavaScript Object Notation) is used to store structured data. Python provides the json module to read/write JSON files.
Example:
import json
# Data to write
data = {
"name": "Chinmaya",
"age": 25,
"skills": ["Python", "OOP", "File Handling"]
}
# Writing JSON to file
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
# Reading JSON from file
with open("data.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data)
Output:
{'name': 'Chinmaya', 'age': 25, 'skills': ['Python', 'OOP', 'File Handling']}
This section covers all essential Python file handling concepts, including file modes, reading/writing methods, and working with JSON for structured data storage and retrieval.