Revision Notes for CSV File Handling in Python(Class 12 Computer Science)

 Revision Notes for CSV File Handling in Python. This topic is part of the File Handling Unit and usually carries 3-5 Marks (often a coding question).


1. What is a CSV File?

  • Full Form: Comma Separated Values.

  • Nature: It is a standard Text File.

  • Structure: Stores tabular data (rows and columns) in plain text form.

  • Default Delimiter: Comma (,).

  • Module Required: import csv


2. The Golden Rule: Opening a CSV File

When opening a CSV file, you MUST use the argument newline=''.

  • Why? In Windows, Python converts \n to \r\n automatically. If you don't use newline='', your CSV file will have blank lines between every row.

  • Syntax:

    Python
    f = open("data.csv", "w", newline='')
    

3. Writing to a CSV File

You need a Writer Object.

Steps:

  1. Open file in 'w' (Write) or 'a' (Append) mode.

  2. Create a writer object: wo = csv.writer(file_handle).

  3. Write data using methods.

Methods:

  • writerow(list): Writes a single row (takes a list).

  • writerows(nested_list): Writes multiple rows at once (takes a list of lists).

Code Pattern:

Python
import csv
data = ["Roll", "Name", "Marks"]
row1 = [101, "Amit", 95]

with open("student.csv", "w", newline='') as f:
    wo = csv.writer(f)
    wo.writerow(data)      # Writing Header
    wo.writerow(row1)      # Writing Single Record
    # OR
    # wo.writerows([data, row1])

4. Reading from a CSV File

You need a Reader Object.

Steps:

  1. Open file in 'r' (Read) mode.

  2. Create a reader object: ro = csv.reader(file_handle).

  3. Iterate through the reader object (it acts like a list of rows).

Key Concept:

  • csv.reader returns data as a List of Strings.

  • Example: Even if the file has 101, Python reads it as '101'. You must typecast it to int if doing calculations.

Code Pattern:

Python
import csv
with open("student.csv", "r") as f:
    ro = csv.reader(f)
    for row in ro:
        # row is a list, e.g., ['101', 'Amit', '95']
        print(row[0], row[1]) 

5. Custom Delimiters

Sometimes CSV files use a separator other than a comma (like a tab or a pipe |).

  • Syntax: Pass delimiter argument.

    Python
    reader = csv.reader(f, delimiter='\t') # For Tab separated
    writer = csv.writer(f, delimiter='|')  # For Pipe separated
    

6. Exam Cheat Sheet: Common Coding Questions

Scenario A: Create a CSV file (Taking User Input)

Python
import csv
def create_csv():
    f = open("inventory.csv", "w", newline='')
    wo = csv.writer(f)
    wo.writerow(["ID", "Product", "Price"]) # Header
    while True:
        pid = int(input("ID: "))
        name = input("Name: ")
        price = float(input("Price: "))
        wo.writerow([pid, name, price])
        ch = input("More? (y/n): ")
        if ch == 'n': break
    f.close()

Scenario B: Search and Display logic

Question: Display products with Price > 500.

Python
import csv
def search_csv():
    f = open("inventory.csv", "r")
    ro = csv.reader(f)
    next(ro) # OPTIONAL: Skips the header row
    for row in ro:
        # row[2] is the price, but it is a String!
        if float(row[2]) > 500: 
            print(row)
    f.close()

7. Common Syllabus Errors (Don't do these!)

  1. Forgetting newline='': Result = Empty lines in output file.

  2. Forgetting Typecasting: row[2] > 500 will cause an error because row[2] is a string '900'. You must compare int(row[2]) > 500.

  3. Mixing Syntax: Using pickle.load() on a CSV file. (Wrong! Use csv.reader).

Comments

Popular Posts