How to Read Csv File and Store in List in Python Using File Operations

This article explains how to load and parse a CSV file in Python.
First of all, what is a CSV ?
CSV (Comma Separated Values) is a simple file format used to shop tabular information, such equally a spreadsheet or database. A CSV file stores tabular information (numbers and text) in evidently text. Each line of the file is a data record. Each record consists of i or more fields, separated by commas. The use of the comma equally a field separator is the source of the proper name for this file format.
For working CSV files in python, in that location is an inbuilt module called csv.

Reading a CSV file

Python

import csv

filename = "aapl.csv"

fields = []

rows = []

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

csvreader = csv.reader(csvfile)

fields = adjacent (csvreader)

for row in csvreader:

rows.append(row)

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

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

print ( '\nFirst v rows are:\due north' )

for row in rows[: 5 ]:

for col in row:

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

impress ( '\due north' )

The output of the above programme looks like this:

The above example uses a CSV file aapl.csv which tin can exist downloaded from here.
Run this programme with the aapl.csv file in the same directory.
Let usa try to sympathize this piece of code.

with open up(filename, 'r') every bit csvfile:     csvreader = csv.reader(csvfile)
  • Here, nosotros starting time open the CSV file in READ mode. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object as csvreader.
fields = csvreader.next()
  • csvreader is an iterable object. Hence, .next() method returns the electric current row and advances the iterator to the next row. Since the first row of our csv file contains the headers (or field names), nosotros salvage them in a list called fields.
for row in csvreader:         rows.append(row)
  • Now, we iterate through the remaining rows using a for loop. Each row is appended to a list called rows. If yous effort to impress each row, i tin observe that a row is nothing merely a list containing all the field values.
print("Full no. of rows: %d"%(csvreader.line_num))
  • csvreader.line_num is nada just a counter which returns the number of rows that have been iterated.

Writing to a CSV file

Python

import csv

fields = [ 'Name' , 'Co-operative' , 'Twelvemonth' , 'CGPA' ]

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

[ 'Sanchit' , 'COE' , '2' , '9.1' ],

[ 'Aditya' , 'Information technology' , '2' , 'ix.3' ],

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

[ 'Prateek' , 'MCE' , 'three' , '7.8' ],

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

filename = "university_records.csv"

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

csvwriter = csv.writer(csvfile)

csvwriter.writerow(fields)

csvwriter.writerows(rows)

Permit united states try to understand the above code in pieces.

  • fields and rows have been already defined. fields is a list containing all the field names. rows is a listing of lists. Each row is a list containing the field values of that row.
with open(filename, 'w') as csvfile:     csvwriter = csv.writer(csvfile)
  • Here, nosotros commencement open the CSV file in WRITE mode. The file object is named equally csvfile. The file object is converted to csv.writer object. Nosotros save the csv.writer object equally csvwriter.
csvwriter.writerow(fields)
  • Now we use writerow method to write the first row which is nil simply the field names.
          csvwriter.writerows(rows)
  • We use writerows method to write multiple rows at once.

Writing a lexicon to a CSV file

Python

import csv

mydict = [{ 'branch' : 'COE' , 'cgpa' : 'nine.0' , 'name' : 'Nikhil' , 'yr' : '2' },

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

{ 'branch' : 'IT' , 'cgpa' : '9.three' , 'proper name' : 'Aditya' , 'twelvemonth' : '2' },

{ 'co-operative' : 'SE' , 'cgpa' : '9.five' , 'name' : 'Sagar' , 'twelvemonth' : '1' },

{ 'co-operative' : 'MCE' , 'cgpa' : '7.eight' , 'name' : 'Prateek' , 'year' : '3' },

{ 'branch' : 'EP' , 'cgpa' : 'ix.1' , 'name' : 'Sahil' , 'year' : 'ii' }]

fields = [ 'name' , 'branch' , 'year' , 'cgpa' ]

filename = "university_records.csv"

with open (filename, 'west' ) equally csvfile:

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

writer.writeheader()

writer.writerows(mydict)

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

with open(filename, 'w') every bit csvfile:     writer = csv.DictWriter(csvfile, fieldnames = fields)
  • Hither, the file object (csvfile) is converted to a DictWriter object.
    Here, we specify the fieldnames every bit an argument.
          writer.writeheader()
  • writeheader method just writes the first row of your csv file using the pre-specified fieldnames.
writer.writerows(mydict)
  • writerows method only writes all the rows but in each row, information technology writes only the values(non keys).

So, in the end, our CSV file looks like this:

Important Points:

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

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

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

  • Nosotros detect that the delimiter is not a comma but a semi-colon. Also, the rows are separated by two newlines instead of i. In such cases, we can specify the delimiter and line terminator as follows:
        

Then, this was a cursory, yet concise discussion on how to load and parse CSV files in a python programme.

This blog is contributed by Nikhil Kumar. If you lot like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-squad@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main folio and help other Geeks.
Please write comments if you find annihilation incorrect, or yous desire to share more information about the topic discussed above.


nappercenry1979.blogspot.com

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

0 Response to "How to Read Csv File and Store in List in Python Using File Operations"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel