Working with CSV File in Python (Reading & Writing)

In this tutorial, we are going to explain how to work with CSV file in python. CSV stands for Comma Separated Value and it is like a simplified spreadsheet stored as a plain text file.

To work with CSV file, first, we need to import csv module using import csv which consists very handy methods like csv.reader(), csv.writer() etc for reading and writing on files.

Another thing required to work with files is we must be able to open a file. So, to open a file we use built-in open() function which takes two arguments, first is filename and second is mode.

Creating & Writing to CSV File

First, we try to open test.csv file in w mode which is shortcut for write mode. In this mode if there is no file with the same name then it will be created otherwise if there is file with the same name then its content will be destroyed. After opening file we write some data using csv.writer() as follows:


import csv

file = open('test.csv', 'w')
writer = csv.writer(file)

writer.writerow(['id', 'name', 'salary'])
writer.writerow([123, 'Alan Jackson', 34000])
writer.writerow([124, 'Jeffrey Way', 55000])
writer.writerow([125, 'Raena Jackson', 45000])

file.close()

After running above code it will create test.csv file which looks like:

id,name,salary
123,Alan Jackson,34000
124,Jeffrey Way,55000
125,Raena Jackson,45000

Note: if lines are skipped in generated CSV file and you don't want this behavior then you can replace file = open('test.csv', 'w') by file = open('test.csv', 'w', newline='\n')

Reading from CSV File

Now we open test.csv that is created earlier in r mode which is shortcut for read mode. After opening we read content from CSV file using csv.reader() as follows:


import csv

file = open('test.csv','r')
# you can do file = open('test.csv') only

reader = csv.reader(file)

# print(list(reader))

# Iterating through reader
for row in reader:
    print(row)

file.close()

Output of above program looks like:

['id', 'name', 'salary']
['123', 'Alan Jackson', '34000']
['124', 'Jeffrey Way', '55000']
['125', 'Raena Jackson', '45000']

Now you can do whatever you want to do with CSV file programmatically. So, working with CSV files is pretty easy in python. Enjoy programming!