Read CSV to Array in Python
-
Use
numpy.loadtxt()
to Read a CSV File Into an Array in Python -
Use the
list()
Method to Read a CSV File Into a 1D Array in Python

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. NumPy’s loadtxt()
function 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.
Example:
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.
Example:
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.
Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.
LinkedInRelated Article - Python CSV
- Import Multiple CSV Files Into Pandas and Concatenate Into One DataFrame
- Python Split CSV Into Multiple Files
- Compare Two CSV Files and Print Differences Using Python
- Convert XLSX to CSV File in Python
- Write List to CSV Columns in Python
- Python Write to CSV Line by Line
Related Article - Python Array
- Initiate 2-D Array in Python
- Count the Occurrences of an Item in a One-Dimensional Array in Python
- Python Downsample Array
- Sort 2D Array in Python
- Create a BitArray in Python
- Fix the Iteration Over a 0-D Array Error in Python NumPy