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:
- Import CSV Module:
import csvimports the CSV module. - Open File:
with open(filename, mode='r') as file:opens the file in read mode. - Create CSV Reader:
reader = csv.reader(file)creates a CSV reader object. - Skip Header:
headers = next(reader)reads and skips the header row. - Read Data: The loop
for row in reader:iterates through each row in the CSV file and appends it to thedatalist. - 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!
