SlideShare a Scribd company logo
1 of 28
Download to read offline
File Reading and Writing
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
1
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
 It would be nice if those different versions could share their data
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
2
CONT…..
 A basic approach to share data is the comma separated value
(CSV) format
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
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
3
Spread sheet and corresponding
CSV file
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
4
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:
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
5
CONT…….
 As in our prior knowledge python usually reads a text file as a line at a time.
 each line ends with an “end of line” (EOL) indicator, On Unix and Linux the EOL
indicator is the new line character (‘n’). On Windows it is actually two characters,
one of which is the new line character.
 csv module can handle CSV files correctly regardless of the operating system on
which the files were created.
 special handling of the EOL indicator for CSV files, using a special option when we
open the file: newline=''
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
7
CSV.READER
 Return a reader object which will iterate over lines in the
given csv file.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
8
EXAMPLE PATIENT.CSV
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
10
WITH CSV.READER
 Read each row in form of list
WITHOUT CSV.READER
 Simply prints
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
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 iterable 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).
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
12
CONT…..
 When we’ve finished reading from the file we delete the reader object and
then close the file
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
13
PRINTING SPECIFIC COLOUMN
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
14
“ ”.join(row) ‘,’.join(row)
join each element in the row together
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
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
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
16
SLICING
• Use a range to specify a slice (sub-data)
Format: sample[start : end]
Includes the start index but excludes the last index.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
17
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
18
EXAMPLES USE OF LINE_NUM
 Skipping specific row
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
19
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
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
20
LIST COMPREHENSION
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
21
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
22
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='')
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
23
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
24
TAKING RUN TIME INPUT IN FILE
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
25
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.
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
26
Write Dictionary in
csv.format
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
27
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD
28

More Related Content

What's hot

11 Unit1 Chapter 1 Getting Started With Python
11   Unit1 Chapter 1 Getting Started With Python11   Unit1 Chapter 1 Getting Started With Python
11 Unit1 Chapter 1 Getting Started With PythonPraveen M Jigajinni
 
Computer Science NAAC presentation Pratibha college Chinchwad
Computer Science NAAC presentation Pratibha college ChinchwadComputer Science NAAC presentation Pratibha college Chinchwad
Computer Science NAAC presentation Pratibha college ChinchwadDr.Ashvini Chaudhari Bhongade
 
Operating system overview concepts ppt
Operating system overview concepts pptOperating system overview concepts ppt
Operating system overview concepts pptRajendraPrasad Alladi
 
Operating system and its function
Operating system and its functionOperating system and its function
Operating system and its functionNikhi Jain
 
Presentation on computer generation
Presentation on computer generationPresentation on computer generation
Presentation on computer generationPritam Das
 
Class viii ch-1 networking concepts
Class  viii ch-1 networking conceptsClass  viii ch-1 networking concepts
Class viii ch-1 networking conceptsjessandy
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on pythonShubham Yadav
 
Ppt on different types of computer viruses
Ppt on different types of computer virusesPpt on different types of computer viruses
Ppt on different types of computer virusesjnnj
 
PPT on Internet in Hindi
PPT on Internet in HindiPPT on Internet in Hindi
PPT on Internet in HindiPawan Yadav
 
PRESENTATION ON COMPUTER SYSTEM
PRESENTATION ON COMPUTER SYSTEMPRESENTATION ON COMPUTER SYSTEM
PRESENTATION ON COMPUTER SYSTEMDeepanshu Saini
 
Computer Languages....ppt
Computer Languages....pptComputer Languages....ppt
Computer Languages....ppthashgeneration
 

What's hot (20)

11 Unit1 Chapter 1 Getting Started With Python
11   Unit1 Chapter 1 Getting Started With Python11   Unit1 Chapter 1 Getting Started With Python
11 Unit1 Chapter 1 Getting Started With Python
 
Computer basics
Computer basicsComputer basics
Computer basics
 
Computer Science NAAC presentation Pratibha college Chinchwad
Computer Science NAAC presentation Pratibha college ChinchwadComputer Science NAAC presentation Pratibha college Chinchwad
Computer Science NAAC presentation Pratibha college Chinchwad
 
C language ppt
C language pptC language ppt
C language ppt
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Hardware & Software
Hardware & SoftwareHardware & Software
Hardware & Software
 
Operating system overview concepts ppt
Operating system overview concepts pptOperating system overview concepts ppt
Operating system overview concepts ppt
 
Operating system and its function
Operating system and its functionOperating system and its function
Operating system and its function
 
Presentation on computer generation
Presentation on computer generationPresentation on computer generation
Presentation on computer generation
 
Class viii ch-1 networking concepts
Class  viii ch-1 networking conceptsClass  viii ch-1 networking concepts
Class viii ch-1 networking concepts
 
Ms DOS
Ms DOSMs DOS
Ms DOS
 
Data types in C
Data types in CData types in C
Data types in C
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on python
 
Ppt on different types of computer viruses
Ppt on different types of computer virusesPpt on different types of computer viruses
Ppt on different types of computer viruses
 
PPT on Internet in Hindi
PPT on Internet in HindiPPT on Internet in Hindi
PPT on Internet in Hindi
 
PRESENTATION ON COMPUTER SYSTEM
PRESENTATION ON COMPUTER SYSTEMPRESENTATION ON COMPUTER SYSTEM
PRESENTATION ON COMPUTER SYSTEM
 
Computer Languages....ppt
Computer Languages....pptComputer Languages....ppt
Computer Languages....ppt
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Presentation on input devices
Presentation on input devicesPresentation on input devices
Presentation on input devices
 
Front pages of practical file
Front pages of practical fileFront pages of practical file
Front pages of practical file
 

Similar to Csv python-project

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
 
Active server pages
Active server pagesActive server pages
Active server pagesstudent
 
Data export in matlab alvian zainuddin
Data export in matlab alvian zainuddinData export in matlab alvian zainuddin
Data export in matlab alvian zainuddinAlvianzainuddin
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training Patrick Schroeder
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabvikrammutneja1
 
Jackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVJackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVTatu Saloranta
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv fileskeeeerty
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv filesKeerty Smile
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basicTechglyphs
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19Max Kleiner
 

Similar to Csv python-project (20)

CSV Files-1.pdf
CSV Files-1.pdfCSV Files-1.pdf
CSV Files-1.pdf
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
oops (1).pptx
oops (1).pptxoops (1).pptx
oops (1).pptx
 
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 2 web technologies
Unit 2 web technologiesUnit 2 web technologies
Unit 2 web technologies
 
10863-2016
10863-201610863-2016
10863-2016
 
Active server pages
Active server pagesActive server pages
Active server pages
 
Data export in matlab alvian zainuddin
Data export in matlab alvian zainuddinData export in matlab alvian zainuddin
Data export in matlab alvian zainuddin
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Jackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSVJackson beyond JSON: XML, CSV
Jackson beyond JSON: XML, CSV
 
Xml writers
Xml writersXml writers
Xml writers
 
CSV_FILES.pptx
CSV_FILES.pptxCSV_FILES.pptx
CSV_FILES.pptx
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
Bt0082 visual basic
Bt0082 visual basicBt0082 visual basic
Bt0082 visual basic
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19
 
Intro lift
Intro liftIntro lift
Intro lift
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Csv python-project

  • 1. File Reading and Writing COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 1
  • 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  It would be nice if those different versions could share their data COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 2
  • 3. CONT…..  A basic approach to share data is the comma separated value (CSV) format 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 COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 3
  • 4. Spread sheet and corresponding CSV file COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 4
  • 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: COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 5
  • 6. CONT…….  As in our prior knowledge python usually reads a text file as a line at a time.  each line ends with an “end of line” (EOL) indicator, On Unix and Linux the EOL indicator is the new line character (‘n’). On Windows it is actually two characters, one of which is the new line character.  csv module can handle CSV files correctly regardless of the operating system on which the files were created.  special handling of the EOL indicator for CSV files, using a special option when we open the file: newline='' COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 6
  • 7. 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 7
  • 8. CSV.READER  Return a reader object which will iterate over lines in the given csv file. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 8
  • 9. EXAMPLE PATIENT.CSV COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 9
  • 10. 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 10
  • 11. WITH CSV.READER  Read each row in form of list WITHOUT CSV.READER  Simply prints COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 11
  • 12. 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 iterable 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). COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 12
  • 13. CONT…..  When we’ve finished reading from the file we delete the reader object and then close the file COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 13
  • 14. PRINTING SPECIFIC COLOUMN COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 14
  • 15. “ ”.join(row) ‘,’.join(row) join each element in the row together COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 15
  • 16. 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 COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 16
  • 17. SLICING • Use a range to specify a slice (sub-data) Format: sample[start : end] Includes the start index but excludes the last index. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 17
  • 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 18
  • 19. EXAMPLES USE OF LINE_NUM  Skipping specific row COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 19
  • 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 COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 20
  • 21. LIST COMPREHENSION COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 21
  • 22. 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 22
  • 23. 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='') COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 23
  • 24. 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 24
  • 25. TAKING RUN TIME INPUT IN FILE COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 25
  • 26. 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. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 26
  • 27. Write Dictionary in csv.format COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 27
  • 28. COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, ISLAMABAD 28