Learn Python File Handling: Read, Write, and Work with JSON - Textnotes

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:

  1. r – Read (default)
  2. w – Write (overwrite existing or create new)
  3. a – Append (write at the end)
  4. rb – Read binary
  5. wb – 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()

  1. read() – Reads the entire file
  2. readline() – Reads one line at a time
  3. readlines() – 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()

  1. write() – Writes a string to the file
  2. writelines() – 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.