Python Convert a CSV File into a List
In this tutorial, we will learn how to convert a CSV file into a list in Python and also converting a list back into a CSV file
Convert CSV file into a List
First import the built-in csv
module that simplifies the process of reading and writing CSV files.
Next, open the file in read mode using the open()
function.
Then, iterate over CSV rows and convert each row into a list. Python’s csv.reader
object provides an iterator that yields each row as a list of strings.
import csv
csv_file_path = 'sample.csv'
with open(csv_file_path, 'r') as file:
csv_reader = csv.reader(file)
data_list = []
for row in csv_reader:
data_list.append(row)
for row in data_list:
print(row)
Example Output
Suppose your sample.csv
file contains the following data:
Name,Age,Country
Alice,25,USA
Bob,30,Canada
Eve,22,UK
Running the provided code with this input will produce the following output:
['Name', 'Age', 'Country']
['Alice', '25', 'USA']
['Bob', '30', 'Canada']
['Eve', '22', 'UK']
Convert a List to a CSV File
Now let’s look at the reverse operation of creating a CSV file from a list in Python.
Like before, import the csv
module, then open the file in the write mode and then use the csv.writer
object to write the data from the list into the CSV file.
import csv
data_list = [
['Name', 'Age', 'Country'],
['Alice', '25', 'USA'],
['Bob', '30', 'Canada'],
['Eve', '22', 'UK']
]
csv_file_path = 'output.csv'
with open(csv_file_path, 'w', newline='') as file:
csv_writer = csv.writer(file)
for row in data_list:
csv_writer.writerow(row)
Example Output
After running the provided code, you will find a new CSV file named output.csv
in the same directory as your script. The contents of this file will match the data_list
you defined:
Name,Age,Country
Alice,25,USA
Bob,30,Canada
Eve,22,UK
Conclusion
In this tutorial we saw how to convert a CSV file to a list in Python and then reverse the process by creating a CSV file from a list. Both operations use the built-in csv
module and it’s reader
and writer
functions.