Sometimes, we want to read a text file into a list or an array with Python.
In this article, we’ll look at how to read a text file into a list or an array with Python.
How to read a text file into a list or an array with Python?
To read a text file into a list or an array with Python, we can use csv.reader
.
For instance, we write
import csv
with open('filename.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
# ...
to open filename.csv with open
.
Then we call csv.reader
with the fd
file handle to read the csv file into an iterator.
And then we use the a for loop to loop through the reader
iterator and do what we want with the row
.
Conclusion
To read a text file into a list or an array with Python, we can use csv.reader
.