Working with CSV Files in Python

CSV stands for comma-separated values and CSV files are files with comma-separated values. It is a plain text-based file with data items delimited with commas.

Though values are separated with commas in csv somethings any characters including tabs can be used as a delimiter.

To work with csv files in Python, you have to use the csv module.

Reading csv files

Let’s see how to read values in a csv file using the reader method.


import csv

file = open('data.csv', 'r')

reader = csv.reader(file)

for row in reader:

    print(row)


#outputs

# ['1', '2', '3', '4', '5']

# ['6', '7', '8', '9', '10']

# ['11', '12', '13', '14', '15']

In the case where the csv has a tab delimiter, you can read the csv file thus:


reader = csv.reader(file, delimiter='\t')

Writing csv files

To create or modify a csv file, the csv.writer() method is used. The syntax is shown below:


file = open('data2.csv', 'w', newline='')

Then write the content using the writerow() method or writerows() method.


file = open('data.csv', 'w', newline='')

writer = csv.writer(file)

writer.writerow([1,2,3])

file.close()

You might as well write multiple rows at once using the writerows() method which accepts nested lists.


content = [['Fruit 1', 'Fruit 2', 'Fruit 3'], ['Apple', 'Orange', 'Mango']]

with open('data.csv', 'w', newline='') as file:

    writer = csv.writer(file, delimiter=',')

    writer.writerows(content)

DictReader() method

This method is used to read a csv file but maps the information read as a dictionary.


file = open('data.csv', 'r')

reader = csv.DictReader(file)

for row in reader:

    print(row)

#outputs

# {'Fruit 1': 'Apple', 'Fruit 2': 'Orange', 'Fruit 3': 'Mango'}

# {'Fruit 1': 'Pineapple', 'Fruit 2': 'Pawpaw', 'Fruit 3': 'Grape'}

DictWriter()

This method is used to write a dictionary into a csv file.


labels = ['color1', 'color2']

file = open('data.csv', 'w', newline='')

writer = csv.DictWriter(file, fieldnames=labels)

writer.writeheader()

writer.writerow({'color1':'green', 'color2':'purple'})

writer.writerow({'color1':'orange', 'color2':'white'})

writer.writerow({'color1':'violet', 'color2':'red'})

file.close()

file = open('data.csv', 'r', newline='')

reader = csv.DictReader(file)

for row in reader:

    print(row)

#outputs

# {'color1': 'green', 'color2': 'purple'}

# {'color1': 'orange', 'color2': 'white'}

# {'color1': 'violet', 'color2': 'red'}

Leave a Reply

Your email address will not be published. Required fields are marked *