SlideShare a Scribd company logo
1 of 31
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C H A P T E R 6
Files and
Exceptions
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Introduction to File Input and Output
Using Loops to Process Files
Processing Records
Exceptions
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input
and Output
For program to retain data between the
times it is run, you must save the data
Data is saved to a file, typically on computer
disk
Saved data can be retrieved and used at a
later time
“Writing data to”: saving data on a file
Output file: a file that data is written to
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction to File Input
and Output (cont’d.)
“Reading data from”: process of
retrieving data from a file
Input file: a file from which data is read
Three steps when a program uses a file
Open the file
Process the file
Close the file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Types of Files and File
Access Methods
In general, two types of files
Text file: contains data that has been encoded
as text
Binary file: contains data that has not been
converted to text
Two ways to access data stored in file
Sequential access: file read sequentially from
beginning to end, can’t skip ahead
Direct access: can jump directly to any piece
of data in the file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Filenames and File Objects
Filename extensions: short sequences
of characters that appear at the end of
a filename preceded by a period
Extension indicates type of data stored in the
file
File object: object associated with a
specific file
Provides a way for a program to work with the
file: file object referenced by a variable
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Filenames and File Objects
(cont’d.)
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Opening a File
open function: used to open a file
Creates a file object and associates it with a
file on the disk
General format:
file_object = open(filename, mode)
Mode: string specifying how the file will
be opened
Example: reading only ('r'), writing ('w'),
and appending ('a')
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Specifying the Location
of a File
If open function receives a filename
that does not contain a path, assumes
that file is in same directory as program
If program is running and file is
created, it is created in the same
directory as the program
Can specify alternative path and file name in
the open function argument
Prefix the path string literal with the letter r
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Writing Data to a File
Method: a function that belongs to an
object
Performs operations using that object
File object’s write method used to
write data to the file
Format: file_variable.write(string)
File should be closed using file object
close method
Format: file_variable.close()
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Reading Data From a File
read method: file object method that
reads entire file contents into memory
Only works if file has been opened for reading
Contents returned as a string
readline method: file object method
that reads a line from the file
Line returned as a string, including 'n'
Read position: marks the location of
the next item to be read from a file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Concatenating a Newline to
and Stripping it From a String
In most cases, data items written to a
file are values referenced by variables
Usually necessary to concatenate a 'n' to
data before writing it
Carried out using the + operator in the argument of
the write method
In many cases need to remove 'n'
from string after it is read from a file
rstrip method: string method that strips
specific characters from end of the string
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Appending Data to an
Existing File
When open file with 'w' mode, if the
file already exists it is overwritten
To append data to a file use the 'a'
mode
If file exists, it is not erased, and if it does not
exist it is created
Data is written to the file at the end of the
current contents
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Writing and Reading
Numeric Data
Numbers must be converted to strings
before they are written to a file
str function: converts value to string
Number are read from a text file as
strings
Must be converted to numeric type in order to
perform mathematical operations
Use int and float functions to convert
string to numeric value
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using Loops to Process Files
Files typically used to hold large
amounts of data
Loop typically involved in reading from and
writing to a file
Often the number of items stored in file
is unknown
The readline method uses an empty string
as a sentinel when end of file is reached
Can write a while loop with the condition
while line != ''
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using Python’s for Loop to
Read Lines
Python allows the programmer to write
a for loop that automatically reads
lines in a file and stops when end of file
is reached
Format: for line in file_object:
statements
The loop iterates once over each line in the
file
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Processing Records
Record: set of data that describes one
item
Field: single piece of data within a
record
Write record to sequential access file
by writing the fields one after the other
Read record from sequential access file
by reading each field until record
complete
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Processing Records (cont’d.)
When working with records, it is also
important to be able to:
Add records
Display records
Search for a specific record
Modify records
Delete records
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Exceptions
Exception: error that occurs while a
program is running
Usually causes program to abruptly halt
Traceback: error message that gives
information regarding line numbers
that caused the exception
Indicates the type of exception and brief
description of the error that caused exception
to be raised
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Exceptions (cont’d.)
Many exceptions can be prevented by
careful coding
Example: input validation
Usually involve a simple decision construct
Some exceptions cannot be avoided by
careful coding
Examples
Trying to convert non-numeric string to an integer
Trying to open for reading a file that doesn’t exist
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Exceptions (cont’d.)
Exception handler: code that responds
when exceptions are raised and
prevents program from crashing
– In Python, written as try/except statement
General format: try:
statements
except exceptionName:
statements
Try suite: statements that can potentially raise an
exception
Handler: statements contained in except block
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Exceptions (cont’d.)
If statement in try suite raises
exception:
Exception specified in except clause:
Handler immediately following except clause
executes
Continue program after try/except statement
Other exceptions:
Program halts with traceback error message
If no exception is raised, handlers are
skipped
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Handling Multiple Exceptions
Often code in try suite can throw more
than one type of exception
Need to write except clause for each type of
exception that needs to be handled
An except clause that does not list a
specific exception will handle any
exception that is raised in the try suite
Should always be last in a series of except
clauses
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Displaying an Exception’s
Default Error Message
Exception object: object created in
memory when an exception is thrown
Usually contains default error message
pertaining to the exception
Can assign the exception object to a variable
in an except clause
Example: except ValueError as err:
Can pass exception object variable to print
function to display the default error message
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The else Clause
try/except statement may include an
optional else clause, which appears
after all the except clauses
Aligned with try and except clauses
Syntax similar to else clause in decision
structure
Else suite: block of statements executed after
statements in try suite, only if no exceptions
were raised
If exception was raised, the else suite is skipped
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The finally Clause
try/except statement may include an
optional finally clause, which
appears after all the except clauses
Aligned with try and except clauses
General format: finally:
statements
Finally suite: block of statements after the
finally clause
Execute whether an exception occurs or not
Purpose is to perform cleanup before exiting
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
What If an Exception Is Not
Handled?
Two ways for exception to go
unhandled:
No except clause specifying exception of the
right type
Exception raised outside a try suite
In both cases, exception will cause the
program to halt
Python documentation provides information
about exceptions that can be raised by
different functions
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Summary
This chapter covered:
Types of files and file access methods
Filenames and file objects
Writing data to a file
Reading data from a file and determining
when the end of the file is reached
Processing records
Exceptions, including:
Traceback messages
Handling exceptions

More Related Content

Similar to Files and Exceptions

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
 
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 filesKeerty Smile
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.ssuser00ad4e
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part IArpana Awasthi
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptRaja Ram Dutta
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdfRashmiAngane1
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSVenugopalavarma Raja
 

Similar to Files and Exceptions (20)

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
 
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
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 
File handling
File handlingFile handling
File handling
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
Satz1
Satz1Satz1
Satz1
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 
Python file handling
Python file handlingPython file handling
Python file handling
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 

More from Munazza-Mah-Jabeen (20)

Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
The Standard Template Library
The Standard Template LibraryThe Standard Template Library
The Standard Template Library
 
Object-Oriented Software
Object-Oriented SoftwareObject-Oriented Software
Object-Oriented Software
 
Templates and Exceptions
 Templates and Exceptions Templates and Exceptions
Templates and Exceptions
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
More About Strings
More About StringsMore About Strings
More About Strings
 
Streams and Files
Streams and FilesStreams and Files
Streams and Files
 
Lists and Tuples
Lists and TuplesLists and Tuples
Lists and Tuples
 
Functions
FunctionsFunctions
Functions
 
Pointers
PointersPointers
Pointers
 
Repitition Structure
Repitition StructureRepitition Structure
Repitition Structure
 
Inheritance
InheritanceInheritance
Inheritance
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Arrays and Strings
Arrays and StringsArrays and Strings
Arrays and Strings
 
Objects and Classes
Objects and ClassesObjects and Classes
Objects and Classes
 
Functions
FunctionsFunctions
Functions
 
Structures
StructuresStructures
Structures
 
Loops and Decisions
Loops and DecisionsLoops and Decisions
Loops and Decisions
 
C++ programming basics
C++ programming basicsC++ programming basics
C++ programming basics
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
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
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 

Files and Exceptions

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Files and Exceptions
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output For program to retain data between the times it is run, you must save the data Data is saved to a file, typically on computer disk Saved data can be retrieved and used at a later time “Writing data to”: saving data on a file Output file: a file that data is written to
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to File Input and Output (cont’d.) “Reading data from”: process of retrieving data from a file Input file: a file from which data is read Three steps when a program uses a file Open the file Process the file Close the file
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Types of Files and File Access Methods In general, two types of files Text file: contains data that has been encoded as text Binary file: contains data that has not been converted to text Two ways to access data stored in file Sequential access: file read sequentially from beginning to end, can’t skip ahead Direct access: can jump directly to any piece of data in the file
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Filenames and File Objects Filename extensions: short sequences of characters that appear at the end of a filename preceded by a period Extension indicates type of data stored in the file File object: object associated with a specific file Provides a way for a program to work with the file: file object referenced by a variable
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Filenames and File Objects (cont’d.)
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Opening a File open function: used to open a file Creates a file object and associates it with a file on the disk General format: file_object = open(filename, mode) Mode: string specifying how the file will be opened Example: reading only ('r'), writing ('w'), and appending ('a')
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Specifying the Location of a File If open function receives a filename that does not contain a path, assumes that file is in same directory as program If program is running and file is created, it is created in the same directory as the program Can specify alternative path and file name in the open function argument Prefix the path string literal with the letter r
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Writing Data to a File Method: a function that belongs to an object Performs operations using that object File object’s write method used to write data to the file Format: file_variable.write(string) File should be closed using file object close method Format: file_variable.close()
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Reading Data From a File read method: file object method that reads entire file contents into memory Only works if file has been opened for reading Contents returned as a string readline method: file object method that reads a line from the file Line returned as a string, including 'n' Read position: marks the location of the next item to be read from a file
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Concatenating a Newline to and Stripping it From a String In most cases, data items written to a file are values referenced by variables Usually necessary to concatenate a 'n' to data before writing it Carried out using the + operator in the argument of the write method In many cases need to remove 'n' from string after it is read from a file rstrip method: string method that strips specific characters from end of the string
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Appending Data to an Existing File When open file with 'w' mode, if the file already exists it is overwritten To append data to a file use the 'a' mode If file exists, it is not erased, and if it does not exist it is created Data is written to the file at the end of the current contents
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Writing and Reading Numeric Data Numbers must be converted to strings before they are written to a file str function: converts value to string Number are read from a text file as strings Must be converted to numeric type in order to perform mathematical operations Use int and float functions to convert string to numeric value
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Loops to Process Files Files typically used to hold large amounts of data Loop typically involved in reading from and writing to a file Often the number of items stored in file is unknown The readline method uses an empty string as a sentinel when end of file is reached Can write a while loop with the condition while line != ''
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Python’s for Loop to Read Lines Python allows the programmer to write a for loop that automatically reads lines in a file and stops when end of file is reached Format: for line in file_object: statements The loop iterates once over each line in the file
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Processing Records Record: set of data that describes one item Field: single piece of data within a record Write record to sequential access file by writing the fields one after the other Read record from sequential access file by reading each field until record complete
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Processing Records (cont’d.) When working with records, it is also important to be able to: Add records Display records Search for a specific record Modify records Delete records
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions Exception: error that occurs while a program is running Usually causes program to abruptly halt Traceback: error message that gives information regarding line numbers that caused the exception Indicates the type of exception and brief description of the error that caused exception to be raised
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions (cont’d.) Many exceptions can be prevented by careful coding Example: input validation Usually involve a simple decision construct Some exceptions cannot be avoided by careful coding Examples Trying to convert non-numeric string to an integer Trying to open for reading a file that doesn’t exist
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions (cont’d.) Exception handler: code that responds when exceptions are raised and prevents program from crashing – In Python, written as try/except statement General format: try: statements except exceptionName: statements Try suite: statements that can potentially raise an exception Handler: statements contained in except block
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions (cont’d.) If statement in try suite raises exception: Exception specified in except clause: Handler immediately following except clause executes Continue program after try/except statement Other exceptions: Program halts with traceback error message If no exception is raised, handlers are skipped
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Handling Multiple Exceptions Often code in try suite can throw more than one type of exception Need to write except clause for each type of exception that needs to be handled An except clause that does not list a specific exception will handle any exception that is raised in the try suite Should always be last in a series of except clauses
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Displaying an Exception’s Default Error Message Exception object: object created in memory when an exception is thrown Usually contains default error message pertaining to the exception Can assign the exception object to a variable in an except clause Example: except ValueError as err: Can pass exception object variable to print function to display the default error message
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The else Clause try/except statement may include an optional else clause, which appears after all the except clauses Aligned with try and except clauses Syntax similar to else clause in decision structure Else suite: block of statements executed after statements in try suite, only if no exceptions were raised If exception was raised, the else suite is skipped
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The finally Clause try/except statement may include an optional finally clause, which appears after all the except clauses Aligned with try and except clauses General format: finally: statements Finally suite: block of statements after the finally clause Execute whether an exception occurs or not Purpose is to perform cleanup before exiting
  • 30. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley What If an Exception Is Not Handled? Two ways for exception to go unhandled: No except clause specifying exception of the right type Exception raised outside a try suite In both cases, exception will cause the program to halt Python documentation provides information about exceptions that can be raised by different functions
  • 31. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Summary This chapter covered: Types of files and file access methods Filenames and file objects Writing data to a file Reading data from a file and determining when the end of the file is reached Processing records Exceptions, including: Traceback messages Handling exceptions