Let's discuss an example where we read the contents of the CSV file created in the previous section:
- The first step in reading a CSV file is opening it in read mode:
with open("csv_example.csv", 'r') as csv_file:
- Next, we initialize an instance of the reader class from the CSV module. The contents of the CSV file are loaded into the object csv_reader:
csv_reader = csv.reader(csv_file)
- Now that the contents of the CSV file are loaded, each row of the CSV file could be retrieved as follows:
for row in csv_reader:
print(row)
- Put it all together:
import csv
if __name__ == "__main__":
# initialize csv writer
with open("csv_example.csv", 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)
- When the preceding code snippet is executed (available for download along with this chapter as csv_read.py), the contents of the file are printed row-by-row where each row is a list that contains the comma separated values:
['123', '456', '789']
['Red', 'Green', 'Blue']