Search⌘ K

CSV and Excel Files

Explore how to read and write CSV and Excel files in both MATLAB and Python. This lesson helps you master file handling techniques using MATLAB’s readtable and writetable functions and Python’s csv module and pandas library, enabling efficient data manipulation and storage.

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.

C++
% 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:

C
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.

Python 3.10.4
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 tabular form using the pandas ...