CSV and Excel Files

Learn to read and write CSV and Excel files in MATLAB and Python.

Reading data from a CSV file

To read a CSV file in MATLAB, we can use the readtable() function. This function reads a CSV file and returns a table array, a special type of array representing tabular data.

Press + to interact
main.m
data.csv
% Read the CSV file into a table array
T = readtable('data.csv');
% Display file data
disp(T)

The output of the above code will be:

Press + to interact
Date Time Temperature
______________ _________ ___________
{'06-06-2000'} {'23:00'} {'78°C'}
{'06-06-2000'} {'02:00'} {'72°C'}
{'06-06-2000'} {'12:20'} {'64°C'}
{'06-06-2000'} {'06:50'} {'66°C'}
{'06-06-2000'} {'03:32'} {'49°C'}

The code above reads the CSV file data.csv into a table array T.

To read a CSV file in Python, we can use the CSV module to parse the file and read its contents into a list of rows.

Press + to interact
main.py
data.csv
import csv
with open('data.csv', 'r') as myFile:
reader = csv.reader(myFile)
for row in reader:
print(row)

This code opens the CSV file data.csv in read mode, reads the contents of the file into a list of rows using the csv.reader() function, and then prints the contents of the list.

We can display the above data in ...