MCS-201 · Unit 16

Data Access Using Python

Section 7 of 7

Block 4 · Unit 16Data Access Using Python11 min · Section 7 of 7

16.7CSV Files in Python

Covers IGNOU MCS-201 §16.6

A CSV (comma-separated values) file is a plain-text table: one record per line, fields separated by a delimiter, usually a comma. Spreadsheets, databases and data-science tools can all import and export CSV, which makes it the most common format for moving tabular data between programs.

The CSV format

marks.csv
name,course,python,dbms
Asha,MCA,78,85
Ravi,MCA,92,74
Neha,BCA,65,90
Arun,MCA,88,81
  • The first line is usually a header row of column names.
  • Fields containing the delimiter are put in quotes: "Delhi, India".
  • Other delimiters are possible: tab (\t), semicolon (;) or colon (:).

The csv module (standard library)

ToolUse
csv.reader(f)Iterates rows as lists of strings
csv.DictReader(f)Iterates rows as dictionaries keyed by the header
csv.writer(f), writer.writerow(row)Writes rows (quotes fields when needed)
delimiter=";"Reads or writes another delimiter

Open CSV files with newline="", as the csv documentation recommends, so that line endings are handled correctly on every system.

pandas

pandas (pip install pandas; included in Anaconda) loads a CSV file into a DataFrame, a table with labelled columns, in one call: df = pd.read_csv("file.csv"). Columns are selected with df["column"], and each column has statistics methods: mean(), sum(), max(), min(), count(), median(), std() (sample standard deviation) and var() (sample variance); describe() shows them all at once.

By default read_csv treats the first line as the header. For a file without a header row, pass header=None, or give the names with names=[...].

Key takeaways

  • CSV: plain-text rows, delimiter-separated fields, usually a header line.
  • csv.reader/DictReader read, csv.writer writes; open with newline="".
  • pd.read_csv returns a DataFrame; use header=None or names= if there is no header.
  • Column methods: mean, sum, max, min, count, median, std, var, describe.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which standard Python module reads and writes CSV files?

Show answer

Answer: C. csv

The csv module is part of the standard library; pandas is a separate third-party package.

Question 2 · multiple choice

What type are the values returned by csv.reader?

Show answer

Answer: B. Strings

The csv module does no type conversion; use int() or float() as needed.

Question 3 · multiple choice

A file has 100 data lines and no header line. How many rows does pd.read_csv(path) give?

Show answer

Answer: C. 99

The first line is taken as column names; pass header=None or names=[...] to keep all 100.

Question 4 · multiple choice

What does df["marks"].median() return for marks 40, 90, 60?

Show answer

Answer: C. 60.0

Sorted, the values are 40, 60, 90, and the middle value is 60; 63.33 is the mean.

Question 5 · multiple choice

Why should CSV files be opened with newline="" when using the csv module?

Show answer

Answer: C. So the module handles line endings itself and does not produce blank lines or broken records

The csv documentation recommends it, because the module manages \r\n line endings and newlines inside quoted fields.

Question 6 · short answer

Write a program that reads sales.csv (columns region and amount) with pandas and prints the total and average amount, and the total for each region.

Show worked answer

import pandas as pd, df = pd.read_csv("sales.csv"), then print("Total:", df["amount"].sum()), print("Average:", df["amount"].mean()) and print(df.groupby("region")["amount"].sum()). read_csv uses the header line for column names; groupby("region") splits the rows by region and sum() adds the amounts in each group.

↑ ↓ move↵ openTab switch type