Reading and Writing CSV Files in Python Using the csv Module (newline='')

⚡ Direct Answer & Key Takeaway

To read and write Comma-Separated Values (CSV) files cleanly in Python for CBSE Class 12 (083), import the built-in `csv` module and always pass `newline=''` inside `open()`. On Windows, omitting `newline=''` causes `csv.writer` to emit an extra `\r\n` sequence, inserting blank lines between records. Use `writerow()` for a single row list, `writerows()` for nested lists, and iterate over `csv.reader(file)`, converting numeric fields with `int()` or `float()` since every read element is a string.

1. Why newline='' Prevents Blank Rows on Windows

Python's built-in `csv` module manages its own line endings according to RFC 4180 by appending `\r\n` (carriage return followed by line feed) at the end of each record by default. When you open a file in text write mode without specifying `newline=''`, Python's universal newline translation layer intercepts every `\n` emitted by `csv.writer` and converts it into the operating system's native line separator. On Windows, the OS separator is already `\r\n`, so the `\r\n` written by `csv.writer` becomes `\r\r\n`. When `csv.reader` or Notepad later parses that file, the extra `\r` is interpreted as an empty line between every stored record. Passing `newline=''` disables automatic newline translation cleanly so the `csv` module controls line endings directly across Windows, macOS, and Linux.

  • `newline=''` is an empty string (two single quotes), not a space `' '` or `'\n'`.
  • Apply `newline=''` for both writing (`'w'`, `'a'`) and reading (`'r'`) CSV files.
  • If a field contains an embedded newline inside quotes, `newline=''` preserves it safely.

2. Writing Rows with writerow() vs writerows() and Custom Delimiters

Once a file is opened with `open('marks.csv', 'w', newline='')`, instantiate a writer object using `writer = csv.writer(file_obj)`. To write a header row or one individual record, pass a flat Python list or tuple to `writer.writerow(['RollNo', 'Section', 'Marks'])`. When inserting an entire dataset stored as a list of lists, `writer.writerows(records)` iterates internally and writes every sublist in one call, which is concise and less error-prone in five-mark board answers. You can also switch the separator character using the `delimiter` parameter, such as `csv.writer(f, delimiter='|')` or `delimiter='\t'` for tab-separated files. If any value contains the active delimiter, `csv.writer` automatically wraps that field in double quotes so parsing stays unambiguous. Always close the file explicitly or use a `with` context manager so buffered rows flush to disk.

  • `writerow(row)` expects a 1D sequence; passing a nested list writes Python bracket notation into a single cell.
  • `writerows(rows)` expects a 2D iterable (list of lists or tuples) and returns `None`.
  • Use mode `'a'` instead of `'w'` when adding new records to an existing CSV without wiping headers.

3. Iterating Safely Over csv.reader() and Skipping Headers

Calling `reader = csv.reader(file_obj)` returns an iterator rather than a list, yielding one list of strings on each iteration. Because CSV is plain text, integers like `92` and decimals like `88.5` are returned as `'92'` and `'88.5'`. Before performing arithmetic comparisons or totals, convert numeric columns explicitly with `int(row[2])` or `float(row[2])`, otherwise `'9' > '85'` evaluates to `True` under lexicographical string comparison. To bypass the column title row, call `header = next(reader, None)` once before your `for` loop. Using the two-argument form of `next()` safely returns `None` instead of raising `StopIteration` if the CSV file happens to be empty. Finally, guard against blank trailing lines with `if not row: continue`, ensuring `row[0]` never triggers an `IndexError` during board exam practical evaluation.

  • `csv.reader` yields every row as `list[str]`, regardless of the original data types written.
  • Convert the iterator via `list(reader)` only when you need random indexing or multiple passes.
  • Passing `delimiter=';'` to `csv.reader` must match the delimiter used by `csv.writer`.

4. Write and Read Student Marks CSV with newline=''

import csv
import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    csv_path = os.path.join(tmp_dir, "student_marks.csv")

    header = ["RollNo", "Section", "Marks"]
    rows = [
        [101, "12-A", 88],
        [102, "12-B", 94],
        [103, "12-A", 79],
        [104, "12-C", 91],
    ]

    with open(csv_path, "w", newline="", encoding="utf-8") as fout:
        writer = csv.writer(fout)
        writer.writerow(header)
        writer.writerows(rows)

    with open(csv_path, "r", newline="", encoding="utf-8") as fin:
        reader = csv.reader(fin)
        col_names = next(reader, None)
        print("Header:", col_names)
        total = 0
        count = 0
        for row in reader:
            if not row:
                continue
            roll, sec, marks = int(row[0]), row[1], int(row[2])
            total += marks
            count += 1
            print(f"Roll {roll} ({sec}): {marks}")
        print(f"Class Average: {total / count:.2f}")

Verified Console / Dry-Run Output:

Header: ['RollNo', 'Section', 'Marks']
Roll 101 (12-A): 88
Roll 102 (12-B): 94
Roll 103 (12-A): 79
Roll 104 (12-C): 91
Class Average: 88.00

5. CBSE Class 12 CSV Module Functions & Parameters Reference

Function / ParameterPurposeArgument TypeBoard Exam Note
open(..., newline='')Disables OS newline translationEmpty string ''Prevents blank lines on Windows
csv.writer(file, delimiter=',')Creates CSV writer objectFile object, optional charDefault delimiter is comma ','
writer.writerow(row)Writes one record to CSV1D list or tupleUse for header or single entry
writer.writerows(rows)Writes multiple records at once2D list of lists/tuplesFaster for bulk record insertion
csv.reader(file)Returns row-by-row iteratorFile objectEach yielded row is list[str]
🎯 1-on-1 Live Mentorship & Free Study Kit

Master CBSE Class 12 File Handling in 1:1 Practice

Practice CSV, binary, and text file board questions live with a mentor in 4Achievers Junior 1-on-1 and 1:4 Micro-Pods for Grades 3-12.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Omitting newline='' in open(), which writes \r\r\n on Windows and creates blank rows ([]) during reading.
  • Avoid Mistake: Passing a nested 2D list to writerow() instead of writerows(), resulting in stringified brackets inside one column.
  • Avoid Mistake: Comparing numeric columns like row[2] > 80 without casting int(row[2]), which raises TypeError in Python 3.
  • Examiner / Mentor Tip: State the exact role of newline='' in one sentence if asked in viva: it suppresses universal newline translation so csv handles \r\n cleanly.
  • Examiner / Mentor Tip: In 5-mark CBSE file-handling questions, always open the file using with open(...) or explicitly call f.close() to earn full syntax marks.
  • Examiner / Mentor Tip: When counting rows in a CSV that includes a header, call next(reader, None) first so the header is not counted as a record.

7. Interactive Concept Check Quiz

Question: What happens on Windows when you write rows with csv.writer(f) after opening a file using open('data.csv', 'w') without newline=''?

8. Frequently Asked Questions

Do we need newline='' when opening a CSV file in read mode ('r')?
Yes. Passing newline='' in read mode ensures that fields containing embedded newlines inside quotes are parsed accurately without premature line splitting.
What data type does csv.reader return for numeric fields like 94 or 78.5?
csv.reader always returns every cell as a Python str inside a list, so you must cast numeric values using int() or float() before performing calculations.
Can we append a new record to an existing CSV without overwriting previous data?
Yes, open the file in append mode using open('file.csv', 'a', newline='') and call writer.writerow(record) without rewriting the header row.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class