Read a Csv in Reverse Order Python

Practise you lot know what mechanism works backside storing tabular data into a plain text file? The answer is CSV(Comma Separated Values) file which allows putting data into a plain-text format. In this commodity on "How to Read CSV File in Python", we volition be learning how to read, write and parse a CSV file in Python.

The following aspects will be discussed in detail:

    • What is a CSV File and its uses?
    • Why is CSV File format used?
    • Python CSV module
      • CSV module functions
    • Operations to perform Write, read a CSV file in Python

Let'due south get started.

What is a CSV File and its uses?

A CSV(Comma Separated Values) is a plain-text file format used to store tabular data such as a spreadsheet or a database. Information technology substantially stores a tabular information which comprises of numbers and text into plain text. Most of the online services give users the freedom to consign data from the website into CSV file format. CSV Files by and large open into Excel and nearly all the databases take dissimilar specific tools to let the import of the same.

Every line of the file is chosen a tape. And each record consists of fields that are separated by commaswhich are also known every bit "delimiter" which is the default delimiter, others include pipe(|), semicolon(;). Given below is a structure of a Normal CSV File separated by a comma, I am making utilise of a titanic CSV file.

Structure

          Rider          ,          Id          ,          Survived          ,          Pclass          ,          Name          ,          Sexual activity.Historic period                    1,0,3 Braund          ,                    Mr. Owen Harris ,male, 22                    2,i,1 Cumings          ,                    Mrs. John Bradley (Florence Briggs Thayer), female,38                    3,1,iii Heikkinen          ,                    Miss. Laina ,female, 26                    4,i,1 Futrelle          ,                    Mrs. Jacques Heath (Lily May Peel),female,35        

Moving on allow's talk about the reason backside usage of CSV File format.

Why is CSV File Format Used?

CSV is a plain-text file which makes it easier for data interchange and also easier to import onto spreadsheet or database storage. For example: You might want to export the data of a certain statistical analysis to CSV file so import it to the spreadsheet for further assay. Overall it makes users working experience very like shooting fish in a barrel programmatically. Any language supporting a text file or string manipulation similar Python can
work with CSV files directly.


Moving ahead, let'south run across how Python natively uses CSV.

Python CSV module

Python uses a CSV package which is a part of the standard library, so you need not install it.

import csv        

Now let me prove you the different CSV functions.

CSV Module Functions

Under the CSV module, you can find the post-obit functions:

Functions

Description

csv.field_size_limit

It returns the maximum field size

csv.get_dialect

Fetches the dialect associated with proper name

csv.list_dialects

Displays all the registered dialects

csv.reader

Read information from csv file

csv.register_dialect

Dialect associated with a proper noun

 csv.writer

Writes data to a csv file

 csv.unregister_dialect

It deletes the dialect associated with the name dialect registry

 csv.QUOTE_ALL

Quotes everything irrespective of the type

 csv.QUOTE_MINIMAL

Quotes special character field

csv.QUOTE_NONNUMERIC

Quotes fields that are not numeral

csv.QUOTE_NONE

  Doesn't quote annihilation in output

Allow'southward move ahead and come across from the coding perspective of the different operations on the CSV file in Python.

Operations On CSV file in Python

Y'all can perform several manipulations once a CSV file is loaded. I am going to show the read and write operations on a CSV file in Python.

 Read CSV file in Python:

import csv   with open up('Titanic.csv','r') as csv_file: #Opens the file in read mode     csv_reader = csv.reader(csv_file) # Making utilise of reader method for reading the file       for line in csv_reader: #Iterate through the loop to read line by line         print(line)        

Output:


Read CSV file in Python

Here, as y'all tin meet from the output, I take made use of Titanic CSV File. And all the fields are separated by a comma, File is read into Python.

Moving ahead, let's see how you can write to a CSV file.

Write to CSV file in Python:

import csv  with open('Titanic.csv', 'r') equally csv_file:     csv_reader = csv.reader(csv_file)      with open('new_Titanic.csv', 'w') as new_file: # Open a new file named 'new_titanic.csv' under write mode         csv_writer = csv.author(new_file, delimiter=';') #making use of write method          for line in csv_reader: # for each file in csv_reader             csv_writer.writerow(line) #writing out to a new file from each line of the original file        

Output:
Write-CSV-read CSV File in Python-Edureka
Now this mode of working with CSV file using a reader and writer method is one of the most mutual approaches. Let'due south motility on and see how you can do the same affair using a python dictionary.

Read CSV file equally Lexicon:

import csv   with open('Titanic.csv','r') every bit csv_file: #Open up the file in read way     csv_reader = csv.DictReader(csv_file) #use dictreader method to reade the file in dictionary       for line in csv_reader: #Iterate through the loop to read line by line         print(line)        

Output:
Read-csv-dict-How to read CSV file in Python-Edureka
Equally yous can see from the output, field has been replaced and they now act as a 'fundamental' of dictionary.

Allow's meet how we can write to a CSV file equally dictionary.

Write to CSV file as Dictionary

import csv   mydict = [{'Passenger':'1', 'Id':'0', 'Survived':'iii'}, #key-value pairs every bit dictionary obj           {'Rider':'2', 'Id':'1', 'Survived':'1'},           {'Rider':'3', 'Id':'1', 'Survived':'3'}]   fields = ['Passenger', 'Id', 'Survived'] #field names  filename = 'new_Titanic.csv' #name of csv file  with open up('new_Titanic.csv', 'w')equally new_csv_file: #open up a new file 'new_titanic,csv' under write mode     writer = csv.DictWriter(new_csv_file, fieldnames=fields)      writer.writeheader() #writing the headers(field names)      author.writerows(mydict) #writing data rows        

Output:
Write-csv-dict-How to read csv in python-Edureka

Allow's see how to read a CSV file in python as pandas.

Read CSV file every bit Pandas:

import pandas #install pandas package  result = pandas.read_csv('Titanic.csv') #read the csv file  impress(upshot) # print result        

Output:
Read-csv-pandas-How to read csv file in python-Edureka

This brings united states to the end of our article "How to read CSV File in Python". I hope you are clear with all the concepts related to CSV, how to read and write it,  how to read and write CSV as a dictionary and how to read CSV as pandas.

    Make sure you do every bit much as possible and revert your feel.

    Got a question for u.s.a.? Please mention it in the comments section of this "How to read CSV File in Python" commodity and we will get back to you every bit soon every bit possible. To get in-depth knowledge of Python along with its various applications, y'all can enroll at present with our alive Python course preparation with 24/7 support and lifetime access.

    baughmansual1946.blogspot.com

    Source: https://www.edureka.co/blog/python-csv-files/

    Related Posts

    0 Response to "Read a Csv in Reverse Order Python"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel