Python working with csv files

Python has built-in libraries to handle CSV files, making it easy to read from, write to, and process these file formats. Here are examples of how to work with both CSV files.

Python’s csv module provides functionality to handle CSV (Comma-Separated Values) files.

Reading from a CSV File


import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

csv.reader(file): Reads the CSV file line by line, where each row is a list.

Writing to a CSV File


import csv

data = [
    ["Name", "Age", "City"],
    ["John", 35, "London"],
    ["Tom", 30, "New York"],
]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

csv.writer(file): Creates a writer object.

writer.writerows(data): Writes multiple rows to the file.

Using a Dictionary with CSV Files

The DictReader and DictWriter classes allow you to work with CSV data as dictionaries, which can be more intuitive.

Reading with DictReader


import csv

with open("data.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)  # Each row is a dictionary

Writing with DictWriter


import csv

data = [
    {"Name": "John", "Age": 35, "City": "London"},
    {"Name": "Tom", "Age": 30, "City": "New York"},
]

with open("data.csv", "w", newline="") as file:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()  # Writes the field names as headers
    writer.writerows(data)

Python working with csv files – Interview Questions

Q 1: How do you read CSV files in Python?
Ans: Using the csv module with csv.reader() or DictReader().
Q 2: How do you write CSV files in Python?
Ans: Using csv.writer() or DictWriter() methods.
Q 3: What delimiter is used in CSV files?
Ans: By default, a comma , separates values.
Q 4: Can you specify a custom delimiter?
Ans: Yes, using the delimiter parameter.
Q 5: Is the CSV module built-in in Python?
Ans: Yes, no installation is required.

Python Working_with_csv_files – Objective Questions (MCQs)

Q1. Which module is used for CSV file operations in Python?






Q2. Which method reads a CSV file as rows?






Q3. Which method writes a list of rows to a CSV file?






Q4. Which argument is commonly used to prevent extra blank lines when writing CSV?






Q5. What does DictReader in the CSV module do?






Related Python Working_with_csv_files Topics