First of all, what is CSV?
CSV (comma separated values) — it is a simple file format file used to store tabular data such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file represents a record of data. Each record consists of one or more fields, separated by commas. Using a comma as a field separator is the source of the name for this file format.
There is a built-in module for working with CSV files in Python csv .
Read CSV file
The output of the above program looks like this:
In the above example re used CSV file aapl.csv, which can be downloaded here .
Run this program with the aapl.csv file in the same directory.
Let’s try to understand this piece of code.
with open (filename, ’ r’) as csvfile: csvreader = csv.reader (csvfile)
Here we first open the CSV file in read mode. The file object is named csvfile . The file object is converted to a csv.reader object. We save the csv.reader object as csvreader .
fields = csvreader.next ()
csvreader — it is a repeatable object. Therefore, the .next () method returns the current line and advances the iterator to the next line. Since the first line of our CSV file contains headers (or field names), we store them in a list called fields .
for row in csvreader: rows.append (row)
We now iterate over the remaining rows using a for loop. Each line is added to a list called lines . If you try to print each line, you will find that this line — nothing more than a list containing all the field values.
print ("Total no. of rows:% d"% (csvreader.line_num))
csvreader.line_num — nothing more than a counter that returns the number of lines that have been repeated.
Write to CSV file
Let’s try to understand the above code piece by piece.
- fields and lines are already defined. fields — a list containing all the field names. Strings — this is a list of lists. Each line is a list containing the field values of that line.
with open (filename, ’w’) as csvfile: csvwriter = csv.writer (csvfile)
Here we first open the CSV file in WRITE mode. The file object is named csvfile . The file object is converted to a csv.writer object. We save the csv.writer object as csvwriter .
We now use the writerow method to write the first line, which is nothing more than the field names.
We use the writerows method to write multiple lines at the same time.
Write dictionary to CSV file
In this example, we writing the dictionary mydict to a CSV file.
with open (filename, ’w’) as csvfile: writer = csv.DictWriter (csvfile, fieldnames = fields )
Here the file object ( csvfile ) is converted to a DictWriter object.
Here we are specifying field names as an argument.
The writeheader method just writes the first line of your CSV file using the predefined field names.
The writerows method is simple writes all lines, but writes only values (not keys) on each line.
So at the end our CSV file looks like this:
- In csv modules an optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV format . By default, the CSV module uses the Excel dialect, which makes them compatible with Excel spreadsheets. You can define your own dialect using the register_dialect method.
Here’s an example:
csv.register_dialect (’mydialect’ , delimiter = ’, ’, quotechar = ’ "’ , doublequote = True , skipinitialspace = True , lineterminator = ’’ , quoting = csv.QUOTE_MINIMAL)
Now, by defining a csv.reader or csv.writer object, we can specify the dialect as
csvreader = csv.reader (csvfile, dialect = ’mydialect’ )
- Now let’s assume the CSV file looks like this:
Note that the separator — is not a comma, but a semicolon. Also, the lines section are separated by two newlines instead of one. In such cases, we can specify the line separator and terminator as follows:
csvreader = csv.reader (csvfile, delimiter = ’;’, lineterminator = ’’ )
So this was a short but short discussion on how to download and parse CSV files in a Python program.
This blog is contributed by Nikhil Kumar . If you like Python.Engineering and would like to contribute, you can also write an article using contrib.python.engineering, or email your article to [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.