Student Activity

Student Activity Guide:

1) Reading and Writing Files (Text, CSV, JSON)

  • Write a Python script to read and write a text file.

  • Read data from a CSV file and convert it into a list of dictionaries.

  • Serialize and deserialize JSON data.

Example Code:

# Writing to a text file
with open("example.txt", "w") as file:
    file.write("Hello, World!
Python File Handling")

# Reading a text file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
import csv
# Writing to a CSV file
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "New York"])

# Reading a CSV file
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
import json
# Writing JSON data
person = {"name": "Alice", "age": 25, "city": "New York"}
with open("person.json", "w") as file:
    json.dump(person, file)

# Reading JSON data
with open("person.json", "r") as file:
    data = json.load(file)
    print(data)

Student Exercise:

  • Read a CSV file and filter records based on a condition.

  • Write a Python program that reads JSON data and extracts specific fields.

2) Working with File Paths and Directories

  • Use the os and pathlib modules to interact with file paths.

  • List all files in a directory.

Example Code:

import os
# List all files in a directory
print(os.listdir("."))

from pathlib import Path
# Creating a new directory
Path("new_folder").mkdir(exist_ok=True)

Student Exercise:

  • Write a script that lists all .txt files in a directory.

  • Create a program that renames multiple files in a directory.

3) Error Handling in File Operations

  • Handle errors using try-except blocks while reading/writing files.

Example Code:

try:
    with open("non_existent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found. Please check the file path.")

Student Exercise:

  • Write a Python program that reads a file and handles potential errors such as FileNotFoundError and PermissionError.

Last updated