How to read and write csv files with the help of Python programming language

When one starts their computer programming journey, there are many already builtin libraries and functions they need to explore with the main purpose of stepping their coding skills to the next level. A very useful Python package is the csv, a module which helps the Python programmer with prebuiltin utilities that can deal with comma-separated values.

For those of you who have never been exposed to the csv file format; a csv file is a simply a text file in which each line of data contains values separated by commas. Based on my personal experience with this popular format, it is mostly and widely being used to represent tabular data.

Take a look at the following piece of information.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

‘FirstName’,’LastName’,’Job’
‘Oltjano’,’Terpollari’,’Blogger’

The above piece of information can be easily saved as a .csv file; so copy and paste into your favorite text editor and save it as csvreader.csv like shown below.

csvreader.csv

Now that you have a csv file, it is time to make use of the Python computer programming language to automatically read it.

How to read a .csv file

According to the official Python documentation, the csv module offers the function reader(), which returns a csv.reader object that can be iterated over with the main purpose of reading content.

As far as my experience goes with the csv.reader function, it requires a file object as an input. There are other arguments which one can pass to this function, but they’re not required by default.

Before we can make use of the csv.reader function, we need to generate a file object from our csv file with the help of Python’s already builtin function called open. The code for generating a file object is being shown below.

f_obj = open('csvreader.csv', 'rt')

The above piece of Python code creates a file object by opening the file csvreader.csv in reading mode with the help of the rt option. Now that we have managed to create a file object out of our csv file, we can easily pass it as an argument to the function reader() which is offered by default in the csv module.

As you may already know, before one can make use of the utilities offered by any Python library, he or she has to import it in their interactive session. So let’s import the Python’s csv module like shown below.

import csv

Once we have managed to import the Python’s csv module with the help of the piece of code which is being shown above, we can easily generate a csv.reader object with the help of the following code.

csv_reader = csv.reader(f_obj)

It is now possible to read the content of the csv file by iterating through the above object with a for loop like shown below.

for line in csv_reader:print(line)

Once I managed to execute the piece of Python code shown above on my interactive console, I got the following output.

['FirstName', 'LastName', 'Job']
['Oltjano', 'Terpollari', 'Blogger'] 

As you can see from the output generated above, each line of data from the csv file is converted into a Python list object. Since Python list objects support indexing, one can easily pull out elements from their csv files.

The following piece of Python code makes use of list indexing.

for line in csv_reader:
    print(line[0], line[1], line[2])

Now refresh your Python interactive console and run the following piece of code.

f = open('csvreader.csv', 'rt')
csv_obj = csv.reader(f)
for line in csv_obj:
    print(line[0], line[1], line[2])

If everything works fine after executing the above piece of Python code, the following output should come out on the interactive console.

('FirstName', 'LastName', 'Job')
('Oltjano', 'Terpollari', 'Blogger')

As we have previously discussed in Python articles, the professional way to open a file object is to do it with the help of the Python’s builtin with statement. So lets refactor the code we have written so far to look exactly like the one which is shown below.

with open('csvreader.csv', 'rt') as f:
    csv_obj = csv.reader(f)
    for line in csv_obj:
        print(line[0], line[1], line[2])

How to write csv files

Now that you have learned how to make use of the Python’s builtin csv module to read csv files, it is time to learn how to write csv files through the csv.writer function.

Based on the Python’s official documentation, the csv.writer function returns an object which is responsible for converting the user’s data into delimited strings on the given file-like object. So for the csv.writer to properly work, you need to provide a file-like object to it.

Enough words. Let’s get our hands dirty with some code. Before going any further, make sure to open a new file in writing mode by making use of the piece of code which is shown below.

# the following piece of Python code opens 
# clients.csv in writing mode
w = open('clients.csv', 'w')

Now that we have a file-like object opened in writing mode, we can easily write data to it through the csv.writer function like shown below.

csv_writer = csv.writer(w)
csv_writer.writerow(['FirstName', 'LastName', 'Job'])

You can write as many rows as you want with the help of the csv.writer.writerow function. Once finished writing the rows you want, close the file-like object like shown below and try to access the clients.csv file generated on your current working directory.

w.close()

After running the above piece of Python code on my interactive console, I ended up with a csv file similar to the one I had in the reading section, just with a different name. I highly recommend that you keep the rows and the header in separate Python list objects.

Take a look at the Python code being shown below.

write_obj = open('students.csv', 'w')
csv_writer = csv.writer(write_obj)
header = ['FirstName', 'LastName']
rows = [
        ['oltjano', 'terpollari'],
        ['john', 'doe']
]
csv_writer.writerow(header)
for row in rows:
    csv_writer.writerow(row)
write_obj.close()

Final thoughts

Most of the Python developers make use of the Python’s builtin csv module in their production code. Having done some freelance work with Django, once I had to make use of the csv module to generate tabular data out of csv files. Although there is still a lot to learn about the Python’s csv module, knowing how to write and read csv files is a very good step.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

One thought on “How to read and write csv files with the help of Python programming language”

Leave a Reply

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