How to Read a CSV file in Python

Python is an awesome general purpose programming language, it has become very popular is the recent years. It can be used in anything ranging from developing desktop GUI application, websites to web applications. It is widely used in data analysis and AI projects too. So now you now how awesome Python is, in this tutorial we'll be learning how to read CSV files in python. We'll also be looking into importing CSV files and writing to CSV files.

If you are a video person, you can check out the video tutorial here:



A quick breakdown of the topics involved in this tutorial about handling CSV files in python:

  1. What is a CSV File
  2. Importing a CSV file in Python
  3. Reading a CSV file in Python
  4. Writing to a CSV file in Python

Ok, so let's get started, first of all what is a CSV file?

What is a CSV File?

CSV is an acronym for Comma Separated Values, many programming languages has support for CSV files and python is one of those languages. Although mostly the values in CSV files are separated by a comma, some files may have values separated by tab of semi colon but most of the time separating by comma is used and that is the standard, here's the example of the CSV file that we will be reading using Python in our examples below.

CSV File


csv-file
CSV file

As you can see in the data above, the top row has the header values that is the column titles, the rows below it have the actual values. Now let's see how we can import this file in python.

Importing a CSV file in python

Importing a CSV file in python is pretty easy, you just import it like any other file, and then to read or write, you use the CSV module of python. First let us see how you can import a file in Python.
file_object  = open("filename", "mode") 
So the code above show how you can import a file. You can import any kind of file using this, not only a CSV file.
The first parameter is the filename, in our case you'll need to enter the CSV filename as the first parameter, let's that it is mycsv.csv.
The second parameter is the mode in which you want to open the file. It means are you opening the file for reading or writing or do you want to create a file if it doesn't exist.
You can leave the mode parameter empty, it that case the default mode 't' is used, that means the file is opening as a text file, and that is quite alright in our case since CSV is basically a text file itself. Here's all the modes that you can use with python file operations:

    
Python File Mode

So now we're equipped with how we can read a file or how we can import a CSV file, this is what the final code for us looks like:

my_csv_file = open('mycsv.txt')
Now we'll move no to finally reading the CSV file, to do that we'll use the CSV module provided by Python. CSV module has reader and writer objects that help us read and write CSV files. We can also read and write data in dictionary form using the DictReader and DictWriter classes that are also provided by python.

How to read a CSV file in python

Ok, finally we are here, reading a CSV file is very easy and we'll use the classes discussed above.
First of all, we need to import the CSV module as discussed above.
Import the csv module using the following code:
import csv
Then we open the CSV file using the with keyword
with open('example.csv') as csvfile:
Now we can use the variable csvfile to do operations on the file, first we read the csv file using the reader method of the csv module like this:
readCSV = csv.reader(csvfile, delimiter=',')
The first parameter is the variable that stores the csv file, the second is the delimiter, i.e that separator that is used between the values in our CSV file. Now finally we loop through the rows of the file like this:
for row in readCSV:
        print(row)
        print(row[0])
        print(row[0],row[1],row[2],)
The overall code looks like this:
Example 1
with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row)
        print(row[0])
        print(row[0],row[1],row[2],)
As you can we, we open the file, than read it using the reader method and loop through the rows to get the values we want, now we'll check out another example. In this one we'll do some more operations after reading the values of the CSV file:


Example 2
import csv

with open('mycsv.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'{row[0]} sold {row[1]} units, and made {row[2]} in revenue')
            line_count += 1
    print(f'Processed {line_count} lines.')

In this example, we are using string manipulation to add some string to the csv values and then print it. Now that we've seen how we can read csv file using python, we'll now see how we can write to a csv file using python.

Writing to a CSV file using Python:

We'll not be going much into how to write to a CSV file, but if you are confident with reading the CSV file, you shouldn't have much trouble reading the file too.
We'll write values into the CSV example that we have seen, the columns are dealer name, units sold and revenue.
import csv

with open('mycsv.csv', mode='w') as dealer_csv:
    dealer_writer = csv.writer(dealer_csv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    dealer_writer.writerow(['Major Dealers', '34563', '5937453'])
    dealer_writer.writerow(['Erica Meyers', '21998', '3453599'])
As you can see it is very similar to the reader that we have seen above. To write a row we use the writerow method, and the we have a list that contains the values that we need to insert in the csv file and we are all done!
You'll also notice some extra parameters here:
1. Delimiter: This define what will be used to separate the values from one another, in this case we have set a comma as the delimiter so that means our values will be comma separated
2. Quoterchar: Our values will be within the character
3. Quoting: What kind of quoting we should follow. There are a lot of ways this can be used.

Although we have added a quotechar in the example above, it is completely optional parameter . The quotechar tells the writer which character to use to quote our values or fields when we are writing to the CSV. Finally the quoting optional parameter defines the conditions in which quoting will be used:
The quoting can be set to the following values:
    csv.QUOTE_MINIMAL : writerow() will quote the fields only if they contain the delimiter or the quotechar. By default, this is the case that is used.
    csv.QUOTE_ALL : writerow() will quote all fields in the file.
    csv.QUOTE_NONNUMERIC : writerow() will quote all fields containing text data & then convert all numeric fields to float data type.
    csv.QUOTE_NONE :  writerow() will escape delimiters and not quote them. In this case, you need to provide a value for the escapechar optional parameter.

So in this tutorial, we have seen how we can read a csv file and write to a csv file in python, if you have any queries just let me know in the comments below. Or message me in our social media platforms facebook, instagram or twitter. Happy coding!

More Popular Python Tutorials:

Comments