Python - How To Read CSV to Array in Python

ID : 471

viewed : 336

Tags : PythonPython CSVPython Array

vote vote


The use of CSV files is widespread in the field of data analysis/data science in Python. CSV stands for Comma Separated Values. These types of files are used to store data in the form of tables and records. In these tables, there are a lot of columns separated by commas. One of the tasks in manipulating these CSV files is importing these files in the form of data arrays.

This tutorial will introduce different methods to import CSV files in the form of data arrays.

Use numpy.loadtxt() to Read a CSV File Into an Array in Python

As the name suggests, the open() function is used to open the CSV file. helps in loading the data from a text file. In this function’s arguments, there are two parameters that must be mentioned: file name or the variable in which the file name is stored, and the other one is called delimiter, which denotes the string used for separating the values. The default value of the delimiter is whitespace.


import numpy as np  with open("randomfile.csv") as file_name:     array = np.loadtxt(file_name, delimiter=",")  print(array) 

Here, note that the delimiter value has been set to a comma. Therefore, the separator in the returned array is a comma.

Use the list() Method to Read a CSV File Into a 1D Array in Python

Here we use the csv module of Python, which is used to read that CSV file in the same tabular format. More precisely, the reader() method of this module is used to read the CSV file.

Finally, the list() method takes all the sequences and the values in tabular format and converts them into a list.


import csv  with open("randomfile.csv") as file_name:     file_read = csv.reader(file_name)  array = list(file_read)   print(array) 

Here, we store the data read by the reader() function in a variable and use that variable to convert that data into a list.

  • Related HOW TO?