How to read a CSV file?

0203

To read a CSV file in Python, you can use the csv module. Here's a simple example:

Example Code:

import csv

def read_csv(filename):
    data = []
    with open(filename, mode='r') as file:
        reader = csv.reader(file)
        headers = next(reader)  # Skip the header row
        for row in reader:
            data.append(row)  # Append each row to the data list
    return data

# Usage
csv_data = read_csv('data.csv')
print(csv_data)

Explanation:

  1. Import CSV Module: import csv imports the CSV module.
  2. Open File: with open(filename, mode='r') as file: opens the file in read mode.
  3. Create CSV Reader: reader = csv.reader(file) creates a CSV reader object.
  4. Skip Header: headers = next(reader) reads and skips the header row.
  5. Read Data: The loop for row in reader: iterates through each row in the CSV file and appends it to the data list.
  6. Return Data: Finally, the function returns the list of rows.

Usage:

Call the read_csv function with the filename of your CSV file to read its contents.

If you have any further questions or need more details, feel free to ask!

0 Comments

no data
Be the first to share your comment!