SlideShare a Scribd company logo
1 of 29
File Reading and Writing
CSV
 The spreadsheet is a very popular, and powerful, application for
manipulating data
 Its popularity means there are many companies that provide their own
version of the spreadsheet
CONT…..
it is a text format, accessible to all apps
each line (even if blank) is a row
in each row, each value is separated from the others by a
comma (even if it is blank)
cannot capture complex things like formula
Spread sheet and corresponding
CSV file
CSV format
 As simple as that sounds, even CSV format is not completely
universal ,different apps have small variations
 Python provides a module to deal with these variations called
the csv module
 This module allows you to read spreadsheet info into your
program
 We load the module in the usual way using import:
CONT…
 we would open a CSV file for reading like
this:
 we would open a new CSV file for writing
like this:
“newline” is used for switching to next line(row)
while entering data in row.
CSV.READER
 Return a reader object which will iterate over lines in the
given csv file.
EXAMPLE
PATIENT.CSV
CSV.READER
 First off, we have to actually import the csv module.
 Then we create a very simple function called csv_reader that
accepts a file object.
 Inside the function, we pass the file object into
the csv_reader function, which returns a reader object.
WITH CSV.READER
 Read each row in form of list
WITHOUT
CSV.READER
 Simply prints
READING FROM A CSV
FILE
 How do we read from a CSV file ?
 We open the file (in text mode) for reading (making sure we give open())
 We create a special type of object to access the CSV file (reader object) d which
we create using the reader() function
 The reader object is an iteratable that gives us access to each line of the CSV file
as a list of fields we can use next() directly on it to read the next line of the CSV
file, or we can treat it like a list in a for loop to read all the lines of the file (as lists
of the file’s fields).
CONT…..
 When we’ve finished reading from the file we delete the reader object and
then close the file
PRINTING SPECIFIC COLOUMN
“ ”.join(row) ‘,’.join(row)
join each element in the row together
QUOTING
 The csv module contains a the following quoting options.
 csv.QUOTE_ALL Quote everything, regardless of type.
 csv.QUOTE_MINIMAL Quote fields with special characters
 csv.QUOTE_NONNUMERIC Quote all fields that are not integers or floats
 csv.QUOTE_NONE Do not quote anything on output
EXAMPLE
SLICING
• Use a range to specify a slice (sub-data)
Format: sample[start : end]
Includes the start index but excludes the last index.
ALLOTTING ROW NO. BY
USING “LINE_NUM”
The print() function call prints the number of
the current row and the contents of the row. To
get the row number, use
the Reader object’s line_num variable, which
contains the number of the current line.
EXAMPLES USE OF
LINE_NUM
 Skipping specific row
LISTING THE
DATA
 Using list() on this Reader object returns a list of lists, which you can
store in a variable like data. Entering data in the shell displays the list of
lists
LIST
COMPREHENSION
DICT READER
When iterate over a CSV file, each
iteration of the loop produces a
dictionary. They keys are the names of
the columns (from the first row of the file,
which is skipped over), and the values
are the data from the row being read.
EXAMPLE USE OF DICT
READER
WRITING A CSV FILE
 How do we write to one?
 We open the file (in text mode) for writing (making sure we give open() the newline=''
option).
 We create a special type of object to write to the CSV file “writer object”, which is
defined in the csv module, and which we create using the writer() function
 The writerow() method, that allows us to write a list of fields to the file. The fields can be
strings or numbers or both writerow() will convert them if necessary
 When using writerow() you do not add a new line character (or other EOL indicator) to
indicate the end of the line, writerow() does it for you as necessary
fw= open('output.csv', 'w', newline='')
WRITING USING “WRITEROW”
A Writer object lets you write data to a CSV file. To create a Writer object, you use
the csv.writer() function.
The writerow() method for Writer objects takes a list argument. Each value in the
list is placed in its own cell in the output CSV file.
TAKING RUN TIME INPUT IN FILE
USE OF DELIMITER AND
LINE_TERMINATOR
• If you want to separate cells with a tab character instead of a comma and you want
the rows to be double-spaced.
• Use delimiter and line terminator.
• Passing delimiter='t' and line terminator='nn' changes the character between
cells to a tab and the character between rows to two newlines.
Csv file read and write

More Related Content

What's hot

Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in PythonPooja B S
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introductionSmriti Jain
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileShivaniJayaprakash1
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST Kathirvel Ayyaswamy
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 

What's hot (20)

Data structures using c
Data structures using cData structures using c
Data structures using c
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Servlets
ServletsServlets
Servlets
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 

Viewers also liked

Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Mnh csv python
Mnh csv pythonMnh csv python
Mnh csv pythonpargery
 
Lección 3. Leer un archivo CSV en R
Lección 3. Leer un archivo CSV en RLección 3. Leer un archivo CSV en R
Lección 3. Leer un archivo CSV en RCarlos Pérez Lara
 
Data Source API in Spark
Data Source API in SparkData Source API in Spark
Data Source API in SparkDatabricks
 
Tutorial XML
Tutorial XMLTutorial XML
Tutorial XMLyumaniko
 
Snapchat Visual Marketing Strategy
Snapchat Visual Marketing StrategySnapchat Visual Marketing Strategy
Snapchat Visual Marketing StrategyKatai Robert
 

Viewers also liked (9)

Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Xml
XmlXml
Xml
 
Mnh csv python
Mnh csv pythonMnh csv python
Mnh csv python
 
The CSV File Strikes Back
The CSV File Strikes BackThe CSV File Strikes Back
The CSV File Strikes Back
 
CSV - 2016
CSV - 2016CSV - 2016
CSV - 2016
 
Lección 3. Leer un archivo CSV en R
Lección 3. Leer un archivo CSV en RLección 3. Leer un archivo CSV en R
Lección 3. Leer un archivo CSV en R
 
Data Source API in Spark
Data Source API in SparkData Source API in Spark
Data Source API in Spark
 
Tutorial XML
Tutorial XMLTutorial XML
Tutorial XML
 
Snapchat Visual Marketing Strategy
Snapchat Visual Marketing StrategySnapchat Visual Marketing Strategy
Snapchat Visual Marketing Strategy
 

Similar to Csv file read and write

Csv python-project
Csv python-projectCsv python-project
Csv python-projectRida Khalid
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabvikrammutneja1
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19Max Kleiner
 
String & path functions in vba
String & path functions in vbaString & path functions in vba
String & path functions in vbagondwe Ben
 
Data export in matlab alvian zainuddin
Data export in matlab alvian zainuddinData export in matlab alvian zainuddin
Data export in matlab alvian zainuddinAlvianzainuddin
 
Active server pages
Active server pagesActive server pages
Active server pagesstudent
 
IO and serialization
IO and serializationIO and serialization
IO and serializationbackdoor
 
Please write a code in JAVA to do line editor..Your program will b.pdf
Please write a code in JAVA to do line editor..Your program will b.pdfPlease write a code in JAVA to do line editor..Your program will b.pdf
Please write a code in JAVA to do line editor..Your program will b.pdffazilfootsteps
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfalokindustries1
 

Similar to Csv file read and write (20)

Csv python-project
Csv python-projectCsv python-project
Csv python-project
 
oops (1).pptx
oops (1).pptxoops (1).pptx
oops (1).pptx
 
Unit 2 web technologies
Unit 2 web technologiesUnit 2 web technologies
Unit 2 web technologies
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19
 
Managing console input
Managing console inputManaging console input
Managing console input
 
CSV_FILES.pptx
CSV_FILES.pptxCSV_FILES.pptx
CSV_FILES.pptx
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
String & path functions in vba
String & path functions in vbaString & path functions in vba
String & path functions in vba
 
Data export in matlab alvian zainuddin
Data export in matlab alvian zainuddinData export in matlab alvian zainuddin
Data export in matlab alvian zainuddin
 
Active server pages
Active server pagesActive server pages
Active server pages
 
WEB TECHNOLOGIES Unit 2
WEB TECHNOLOGIES Unit 2WEB TECHNOLOGIES Unit 2
WEB TECHNOLOGIES Unit 2
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
 
Please write a code in JAVA to do line editor..Your program will b.pdf
Please write a code in JAVA to do line editor..Your program will b.pdfPlease write a code in JAVA to do line editor..Your program will b.pdf
Please write a code in JAVA to do line editor..Your program will b.pdf
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 

More from comsats university of science information technology (6)

genomic comparison
genomic comparison genomic comparison
genomic comparison
 
Matlab bioinformatics presentation
Matlab bioinformatics presentationMatlab bioinformatics presentation
Matlab bioinformatics presentation
 
Final chick embryonic-development-ppt
Final chick embryonic-development-pptFinal chick embryonic-development-ppt
Final chick embryonic-development-ppt
 
Bio info
Bio infoBio info
Bio info
 
ANTI CHRIST in ISLAM
ANTI CHRIST in ISLAMANTI CHRIST in ISLAM
ANTI CHRIST in ISLAM
 
courtesy 7C's of communication
courtesy 7C's of communicationcourtesy 7C's of communication
courtesy 7C's of communication
 

Recently uploaded

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Recently uploaded (20)

Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Csv file read and write

  • 2. CSV  The spreadsheet is a very popular, and powerful, application for manipulating data  Its popularity means there are many companies that provide their own version of the spreadsheet
  • 3. CONT….. it is a text format, accessible to all apps each line (even if blank) is a row in each row, each value is separated from the others by a comma (even if it is blank) cannot capture complex things like formula
  • 4. Spread sheet and corresponding CSV file
  • 5. CSV format  As simple as that sounds, even CSV format is not completely universal ,different apps have small variations  Python provides a module to deal with these variations called the csv module  This module allows you to read spreadsheet info into your program  We load the module in the usual way using import:
  • 6. CONT…  we would open a CSV file for reading like this:  we would open a new CSV file for writing like this: “newline” is used for switching to next line(row) while entering data in row.
  • 7. CSV.READER  Return a reader object which will iterate over lines in the given csv file.
  • 9. CSV.READER  First off, we have to actually import the csv module.  Then we create a very simple function called csv_reader that accepts a file object.  Inside the function, we pass the file object into the csv_reader function, which returns a reader object.
  • 10. WITH CSV.READER  Read each row in form of list WITHOUT CSV.READER  Simply prints
  • 11. READING FROM A CSV FILE  How do we read from a CSV file ?  We open the file (in text mode) for reading (making sure we give open())  We create a special type of object to access the CSV file (reader object) d which we create using the reader() function  The reader object is an iteratable that gives us access to each line of the CSV file as a list of fields we can use next() directly on it to read the next line of the CSV file, or we can treat it like a list in a for loop to read all the lines of the file (as lists of the file’s fields).
  • 12. CONT…..  When we’ve finished reading from the file we delete the reader object and then close the file
  • 14. “ ”.join(row) ‘,’.join(row) join each element in the row together
  • 15. QUOTING  The csv module contains a the following quoting options.  csv.QUOTE_ALL Quote everything, regardless of type.  csv.QUOTE_MINIMAL Quote fields with special characters  csv.QUOTE_NONNUMERIC Quote all fields that are not integers or floats  csv.QUOTE_NONE Do not quote anything on output
  • 17. SLICING • Use a range to specify a slice (sub-data) Format: sample[start : end] Includes the start index but excludes the last index.
  • 18. ALLOTTING ROW NO. BY USING “LINE_NUM” The print() function call prints the number of the current row and the contents of the row. To get the row number, use the Reader object’s line_num variable, which contains the number of the current line.
  • 19. EXAMPLES USE OF LINE_NUM  Skipping specific row
  • 20. LISTING THE DATA  Using list() on this Reader object returns a list of lists, which you can store in a variable like data. Entering data in the shell displays the list of lists
  • 22.
  • 23. DICT READER When iterate over a CSV file, each iteration of the loop produces a dictionary. They keys are the names of the columns (from the first row of the file, which is skipped over), and the values are the data from the row being read.
  • 24. EXAMPLE USE OF DICT READER
  • 25. WRITING A CSV FILE  How do we write to one?  We open the file (in text mode) for writing (making sure we give open() the newline='' option).  We create a special type of object to write to the CSV file “writer object”, which is defined in the csv module, and which we create using the writer() function  The writerow() method, that allows us to write a list of fields to the file. The fields can be strings or numbers or both writerow() will convert them if necessary  When using writerow() you do not add a new line character (or other EOL indicator) to indicate the end of the line, writerow() does it for you as necessary fw= open('output.csv', 'w', newline='')
  • 26. WRITING USING “WRITEROW” A Writer object lets you write data to a CSV file. To create a Writer object, you use the csv.writer() function. The writerow() method for Writer objects takes a list argument. Each value in the list is placed in its own cell in the output CSV file.
  • 27. TAKING RUN TIME INPUT IN FILE
  • 28. USE OF DELIMITER AND LINE_TERMINATOR • If you want to separate cells with a tab character instead of a comma and you want the rows to be double-spaced. • Use delimiter and line terminator. • Passing delimiter='t' and line terminator='nn' changes the character between cells to a tab and the character between rows to two newlines.