Scala Program Reading Csv Compare Csv Field

This commodity explains how to load and parse a CSV file in Python.
Start of all, what is a CSV ?
CSV (Comma Separated Values) is a simple file format used to store tabular data, such every bit a spreadsheet or database. A CSV file stores tabular data (numbers and text) in obviously text. Each line of the file is a data record. Each record consists of ane or more fields, separated past commas. The utilize 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 up (filename, 'r' ) as csvfile:

csvreader = csv.reader(csvfile)

fields = next (csvreader)

for row in csvreader:

rows.append(row)

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

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

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

for row in rows[: v ]:

for col in row:

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

print ( '\northward' )

The output of the above program looks like this:

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

with open(filename, 'r') every bit csvfile:     csvreader = csv.reader(csvfile)
  • Here, nosotros kickoff open the CSV file in READ mode. The file object is named equally 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 current row and advances the iterator to the next row. Since the offset row of our csv file contains the headers (or field names), we relieve them in a list called fields.
for row in csvreader:         rows.suspend(row)
  • At present, we iterate through the remaining rows using a for loop. Each row is appended to a list chosen rows. If you attempt to impress each row, one can find that a row is nothing but a list containing all the field values.
impress("Total no. of rows: %d"%(csvreader.line_num))
  • csvreader.line_num is nothing but a counter which returns the number of rows that accept been iterated.

Writing to a CSV file

Python

import csv

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

rows = [ [ 'Nikhil' , 'COE' , '2' , 'nine.0' ],

[ 'Sanchit' , 'COE' , 'two' , '9.1' ],

[ 'Aditya' , 'Information technology' , 'two' , 'ix.three' ],

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

[ 'Prateek' , 'MCE' , '3' , '7.8' ],

[ 'Sahil' , 'EP' , '2' , '9.i' ]]

filename = "university_records.csv"

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

csvwriter = csv.writer(csvfile)

csvwriter.writerow(fields)

csvwriter.writerows(rows)

Let us try to sympathize the above lawmaking in pieces.

  • fields and rows have been already defined. fields is a listing containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row.
with open(filename, 'w') as csvfile:     csvwriter = csv.writer(csvfile)
  • Hither, we first open the CSV file in WRITE mode. The file object is named every bit 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 zilch simply 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' , 'name' : 'Nikhil' , 'twelvemonth' : '2' },

{ 'branch' : 'COE' , 'cgpa' : '9.1' , 'proper name' : 'Sanchit' , 'year' : 'ii' },

{ 'branch' : 'It' , 'cgpa' : '9.3' , 'name' : 'Aditya' , 'year' : '2' },

{ 'branch' : 'SE' , 'cgpa' : '9.5' , 'proper name' : 'Sagar' , 'year' : '1' },

{ 'co-operative' : 'MCE' , 'cgpa' : 'seven.8' , 'name' : 'Prateek' , 'year' : '3' },

{ 'co-operative' : 'EP' , 'cgpa' : '9.1' , 'proper noun' : 'Sahil' , 'year' : '2' }]

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

filename = "university_records.csv"

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

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

writer.writeheader()

author.writerows(mydict)

In this example, nosotros write a dictionary mydict to a CSV file.

with open(filename, 'west') as csvfile:     author = 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 first row of your csv file using the pre-specified fieldnames.
writer.writerows(mydict)
  • writerows method simply writes all the rows but in each row, information technology writes simply the values(not keys).

Then, in the cease, our CSV file looks like this:

Important Points:

  • In csv modules, an optional dialect parameter can be given which is used to define a fix of parameters specific to a particular CSV format. By default, csv module uses excel dialect which makes them uniform 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, nosotros tin can specify the dialect like
this:

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

  • We notice that the delimiter is not a comma just a semi-colon. Also, the rows are separated by two newlines instead of one. In such cases, we tin can specify the delimiter and line terminator as follows:
        

And so, this was a brief, all the same concise word on how to load and parse CSV files in a python plan.

This web log is contributed past Nikhil Kumar. If you like GeeksforGeeks and would similar to contribute, you lot tin also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. Run into your commodity appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or y'all desire to share more data almost the topic discussed above.


wellslefully.blogspot.com

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

Related Posts

0 Response to "Scala Program Reading Csv Compare Csv Field"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel