SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 10
← Back to Course Index

File Handling


On This Page

Module 10: File Handling


10.1  Why File Handling Matters

Real-world data analytics almost always starts with a file — a CSV export from Excel, a JSON response from an API, or a plain text log. File handling lets Python read data from and write data to these files on disk.

ℹ Note
Always close a file after using it to free up system resources. The safest way is the with statement, which closes the file automatically — even if an error occurs.

10.2  Reading Files

► Reading a Text File
with open("students.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("students.txt", "r") as file:
    for line in file:
        print(line.strip())
ModeMeaning
'r'Read (default) — file must already exist
'w'Write — creates a new file or overwrites an existing one
'a'Append — adds to the end of an existing file
'r+'Read and write

10.3  Writing Files

Writing mode ('w') creates a new file or completely overwrites an existing one — use this mode carefully!

► Writing to a File
with open("enrolled_students.txt", "w") as file:
    file.write("Priya Sharma\n")
    file.write("Rahul Verma\n")
    file.write("Anita Desai\n")
print("File written successfully!")
✗ Common Mistake
Using mode 'w' on a file that already has important data will erase everything in it. Always use 'a' (append) if you want to add data without deleting what's already there.

10.4  Appending to Files

► Appending New Data
with open("enrolled_students.txt", "a") as file:
    file.write("Vikram Singh\n")
print("New student added without deleting existing data!")

10.5  Working with CSV Files

CSV (Comma-Separated Values) is the most common data file format in analytics — Excel exports, reports, and datasets are almost always shared as CSV files.

► Reading a CSV File
import csv

with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
► Writing a CSV File
import csv

data = [
    ["Name", "Course", "Fee"],
    ["Priya", "SEO", 12000],
    ["Rahul", "Google Ads", 15000],
]

with open("new_students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)
✓ Instructor Tip
In real data analytics projects, students will more often use pandas.read_csv() instead of the raw csv module — introduce this connection when teaching Module 14 (Pandas).

10.6  Working with JSON Files

JSON (JavaScript Object Notation) is the standard format for APIs and structured configuration data — it looks almost identical to a Python dictionary.

► Reading and Writing JSON
import json

student = {"name": "Priya", "course": "SEO", "fee": 12000}

# Writing JSON to a file
with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

# Reading JSON from a file
with open("student.json", "r") as file:
    data = json.load(file)
    print(data["name"])
Output
Priya

10.7  Real Data Examples

► Real Example: Processing Student Records from CSV
import csv

total_fee = 0
with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        total_fee += int(row["Fee"])

print("Total Fee Collected:", total_fee)
ℹ Real-World Use Case
This exact pattern — read a CSV, loop through rows, and aggregate a column — is one of the most common tasks a Data Analyst performs before even opening pandas.

10.8  Practical Exercises

Basic (5 Questions)

1. Create a text file and write your name and course into it.

2. Read and print the contents of the file you just created.

3. Append one more line to the same file without deleting existing content.

4. Write a small CSV file with 3 students' names and marks.

5. Read the CSV file you created and print each row.

Intermediate (5 Questions)

1. Write a program that counts the number of lines in a text file.

2. Write a program that saves a Python dictionary of student data to a JSON file.

3. Write a program that reads a JSON file back and prints specific fields.

4. Write a CSV file with headers, then read it back using csv.DictReader.

5. Handle the FileNotFoundError gracefully when trying to read a file that doesn't exist.

Advanced (5 Questions)

1. Build a program that reads a CSV of student fees and calculates the total, average, and highest fee.

2. Write a program that reads a text file of student names (one per line) and writes only names starting with 'A' into a new file.

3. Build a simple JSON-based 'Student Database': add a student, save to JSON, and reload it to confirm the data persisted.

4. Write a program that merges two CSV files of student records into a single combined CSV.

5. Build a 'Log Writer' that appends a timestamped entry to a log file every time a function is called.

10.9  Module Quiz (MCQs)

Q1. Which file mode overwrites an existing file?

Q2. Which mode adds data without deleting existing content?

Q3. Which module is used to read/write CSV files?

Q4. What does json.load() do?

Q5. What is the safest way to open a file in Python?

ℹ Answer Key
1-c, 2-b, 3-b, 4-b, 5-b

10.10  Module Assignment

Assignment: Student Fee Report Generator

Expected Output: A working pipeline that reads raw CSV data, computes summary statistics, and saves + reloads them as a structured JSON report.

10.11  Interview Questions — Module 10


10.12  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.