How Do I Read a Csv File of Dataset in Python

This article explains how to load and parse a CSV file in Python.
Showtime of all, what is a CSV ?
CSV (Comma Separated Values) is a elementary file format used to store tabular data, such every bit a spreadsheet or database. A CSV file stores tabular data (numbers and text) in manifestly text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the proper noun for this file format.
For working CSV files in python, there is an inbuilt module called csv.

Reading a CSV file

Python

import csv

filename = "aapl.csv"

fields = []

rows = []

with open (filename, 'r' ) as csvfile:

csvreader = csv.reader(csvfile)

fields = side by side (csvreader)

for row in csvreader:

rows.append(row)

print ("Total no. of rows: % d" % (csvreader.line_num))

print ( 'Field names are:' + ', ' .bring together(field for field in fields))

impress ( '\nFirst 5 rows are:\n' )

for row in rows[: 5 ]:

for col in row:

impress ( "%10s" % col,end = " " ),

impress ( '\n' )

The output of the above program looks like this:

The in a higher place case uses a CSV file aapl.csv which tin can be downloaded from here.
Run this programme with the aapl.csv file in the aforementioned directory.
Let us try to understand this piece of code.

with open(filename, 'r') every bit csvfile:     csvreader = csv.reader(csvfile)
  • Here, we kickoff open the CSV file in READ fashion. The file object is named as csvfile. The file object is converted to csv.reader object. We relieve the csv.reader object as csvreader.
fields = csvreader.next()
  • csvreader is an iterable object. Hence, .next() method returns the current row and advances the iterator to the side by side row. Since the first row of our csv file contains the headers (or field names), we save them in a list called fields.
for row in csvreader:         rows.append(row)
  • Now, nosotros iterate through the remaining rows using a for loop. Each row is appended to a list chosen rows. If you attempt to print each row, one tin find that a row is nada only a listing containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
  • csvreader.line_num is cipher simply a counter which returns the number of rows that have been iterated.

Writing to a CSV file

Python

import csv

fields = [ 'Proper noun' , 'Branch' , 'Twelvemonth' , 'CGPA' ]

rows = [ [ 'Nikhil' , 'COE' , 'ii' , '9.0' ],

[ 'Sanchit' , 'COE' , '2' , 'ix.1' ],

[ 'Aditya' , 'IT' , '2' , '9.three' ],

[ 'Sagar' , 'SE' , 'i' , '9.v' ],

[ 'Prateek' , 'MCE' , 'three' , '7.eight' ],

[ 'Sahil' , 'EP' , '2' , '9.1' ]]

filename = "university_records.csv"

with open up (filename, 'westward' ) as csvfile:

csvwriter = csv.writer(csvfile)

csvwriter.writerow(fields)

csvwriter.writerows(rows)

Let us try to understand the above code in pieces.

  • fields and rows take been already defined. fields is a listing containing all the field names. rows is a list of lists. Each row is a listing containing the field values of that row.
with open(filename, 'due west') equally csvfile:     csvwriter = csv.author(csvfile)
  • Hither, we commencement open the CSV file in WRITE manner. The file object is named every bit csvfile. The file object is converted to csv.writer object. We relieve the csv.writer object equally csvwriter.
csvwriter.writerow(fields)
  • At present we utilize writerow method to write the first row which is cypher but the field names.
          csvwriter.writerows(rows)
  • We use writerows method to write multiple rows at once.

Writing a dictionary to a CSV file

Python

import csv

mydict = [{ 'branch' : 'COE' , 'cgpa' : '9.0' , 'proper noun' : 'Nikhil' , 'twelvemonth' : 'two' },

{ 'branch' : 'COE' , 'cgpa' : '9.ane' , 'name' : 'Sanchit' , 'year' : 'two' },

{ 'co-operative' : 'IT' , 'cgpa' : '9.3' , 'name' : 'Aditya' , 'year' : '2' },

{ 'co-operative' : 'SE' , 'cgpa' : '9.5' , 'proper noun' : 'Sagar' , 'year' : '1' },

{ 'branch' : 'MCE' , 'cgpa' : 'vii.eight' , 'name' : 'Prateek' , 'year' : 'three' },

{ 'branch' : 'EP' , 'cgpa' : '9.ane' , 'proper noun' : 'Sahil' , 'year' : 'ii' }]

fields = [ 'proper noun' , 'branch' , 'twelvemonth' , 'cgpa' ]

filename = "university_records.csv"

with open (filename, 'w' ) every bit csvfile:

writer = csv.DictWriter(csvfile, fieldnames = fields)

writer.writeheader()

writer.writerows(mydict)

In this example, we write a lexicon mydict to a CSV file.

with open(filename, 'westward') as csvfile:     writer = csv.DictWriter(csvfile, fieldnames = fields)
  • Here, the file object (csvfile) is converted to a DictWriter object.
    Here, nosotros specify the fieldnames as an argument.
          writer.writeheader()
  • writeheader method simply writes the beginning row of your csv file using the pre-specified fieldnames.
writer.writerows(mydict)
  • writerows method simply writes all the rows simply in each row, it writes only the values(non keys).

And then, in the stop, our CSV file looks like this:

Important Points:

  • In csv modules, an optional dialect parameter tin can exist given which is used to define a set of parameters specific to a detail CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. Yous can define your own dialect using register_dialect method.
    Hither is an example:
        

Now, while defining a csv.reader or csv.writer object, we tin can specify the dialect like
this:

        
  • Now, consider that a CSV file looks like this in plain-text:

  • We detect that the delimiter is non a comma only a semi-colon. As well, the rows are separated past two newlines instead of ane. In such cases, we tin can specify the delimiter and line terminator equally follows:
        

So, this was a cursory, yet concise word on how to load and parse CSV files in a python program.

This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, yous can also write an article using write.geeksforgeeks.org or post your article to review-squad@geeksforgeeks.org. Meet your commodity appearing on the GeeksforGeeks primary page and help other Geeks.
Please write comments if you find annihilation wrong, or you want to share more information about the topic discussed above.


harristheassion.blogspot.com

Source: https://www.geeksforgeeks.org/working-csv-files-python/

0 Response to "How Do I Read a Csv File of Dataset in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel