How to Upload a Cvs File to Python

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 uncomplicated file format used to shop 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 is a data tape. Each record consists of one or more fields, separated past 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, at that place 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 = next (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))

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

for row in rows[: 5 ]:

for col in row:

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

print ( '\due north' )

The output of the higher up program looks like this:

The higher up instance uses a CSV file aapl.csv which can exist downloaded from here.
Run this program with the aapl.csv file in the aforementioned directory.
Permit us try to understand this piece of lawmaking.

with open(filename, 'r') as csvfile:     csvreader = csv.reader(csvfile)
  • Hither, we 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 salve the csv.reader object as csvreader.
fields = csvreader.adjacent()
  • csvreader is an iterable object. Hence, .side by side() method returns the current row and advances the iterator to the adjacent 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.suspend(row)
  • Now, we iterate through the remaining rows using a for loop. Each row is appended to a list chosen rows. If yous try to print each row, ane can find that a row is nothing simply a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
  • csvreader.line_num is nothing but a counter which returns the number of rows that have been iterated.

Writing to a CSV file

Python

import csv

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

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

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

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

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

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

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

filename = "university_records.csv"

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

csvwriter = csv.author(csvfile)

csvwriter.writerow(fields)

csvwriter.writerows(rows)

Allow us try to empathize the to a higher place code in pieces.

  • fields and rows accept been already defined. fields is a list 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, 'west') equally csvfile:     csvwriter = csv.author(csvfile)
  • Hither, nosotros showtime open the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. Nosotros save the csv.writer object as csvwriter.
csvwriter.writerow(fields)
  • Now we apply writerow method to write the outset row which is nothing but the field names.
          csvwriter.writerows(rows)
  • Nosotros use writerows method to write multiple rows at one time.

Writing a dictionary to a CSV file

Python

import csv

mydict = [{ 'branch' : 'COE' , 'cgpa' : '9.0' , 'name' : 'Nikhil' , 'year' : 'two' },

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

{ 'co-operative' : 'Information technology' , 'cgpa' : 'nine.3' , 'name' : 'Aditya' , 'twelvemonth' : '2' },

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

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

{ 'branch' : 'EP' , 'cgpa' : '9.i' , 'name' : 'Sahil' , 'year' : '2' }]

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

filename = "university_records.csv"

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

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

writer.writeheader()

author.writerows(mydict)

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

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

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

Of import Points:

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

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

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

  • We notice that the delimiter is non a comma but a semi-colon. Also, the rows are separated past 2 newlines instead of ane. In such cases, we can specify the delimiter and line terminator as follows:
        

So, this was a brief, notwithstanding concise discussion on how to load and parse CSV files in a python programme.

This web log is contributed past Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your commodity to review-team@geeksforgeeks.org. See your commodity appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if yous find anything incorrect, or yous want to share more data virtually the topic discussed above.


mcarthurtherroys.blogspot.com

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

0 Response to "How to Upload a Cvs File to Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel