How to import a CSV to list with Python?

Sometimes, we want to import a CSV to list with Python.

In this article, we’ll look at how to import a CSV to list with Python.

How to import a CSV to list with Python?

To import a CSV to list with Python, we can call open to open the CSV and then call csv.reader to read it.

For instance, we write:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)

We call open with the path string to the file.

Then we call csv.reader with the file handle f to read the file and return a iterator.

Then we assign the iterator to reader.

Finally, we convert the reader iterator to a list with list and assign it to data.

Therefore, data is [['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']] if file.csv has:

This is the first line,Line1
This is the second line,Line2
This is the third line,Line3

Conclusion

To import a CSV to list with Python, we can call open to open the CSV and then call csv.reader to read it.