© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.

Slides:



Advertisements
Similar presentations
Chapter 8 Improving the User Interface
Advertisements

C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Head First Python Chapter 4 Persistence: Saving Data to Files SNU IDB Lab.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Chapter 7 Improving the User Interface
 2004 Prentice Hall, Inc. All rights reserved. Chapter 35 – Python Outline 35.1 Introduction First Python Program Python Keywords 35.2 Basic.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Topics Introduction Hardware and Software How Computers Store Data
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 2 - Welcome Application: Introduction to C++
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
General Programming Introduction to Computing Science and Programming I.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 1 Introduction to Computers and Programming.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Chapter 5 Files and Exceptions I. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a file? A.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Exceptions CMSC 201. Overview Exceptions are run-time errors, especially ones that the programmer cannot predict.  example 1: division by zero  example.
Files Tutor: You will need ….
PHP Error Handling Section :I Source: 1.
Agenda Using vi Editor Starting vi Session Command / Input Modes
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Chapter 16 Web Pages And CGI Scripts Department of Biomedical Informatics University of Pittsburgh School of Medicine
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Control Statements 1. Conditionals 2 Loops 3 4 Simple Loop Examples def echo(): while echo1(): pass def echo1(): line = input('Say something: ') print('You.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Introduction to Computing Science and Programming I
Topic: File Input/Output (I/O)
Fundamentals of Python: First Programs
Chapter 7 Text Input/Output Objectives
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Chapter 7 Text Input/Output Objectives
Chapter 12 Exception Handling and Text IO
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Unit-2 Objects and Classes
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
(Oops! When things go wrong)
Topics Introduction to File Input and Output
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Bryan Burlingame 17 April 2019
Chapter 12 Exception Handling and Text IO Part 2
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Presentation transcript:

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Motivations Data stored in the program are temporary; they are lost when the program terminates. To permanently store the data created in a program, you need to save them in a file on a disk or other permanent storage. The file can be transported and can be read later by other programs. There are two types of files: text and binary. Text files are essentially strings on disk. This chapter introduces how to read/write data from/to a text file. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the subject we will introduce in this chapter. 2

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Objectives To open a file, read/write data from/to a file (§13.2) To use file dialogs for opening and saving data (§13.3). To develop applications with files (§13.4) To read data from a Web resource (§13.5). To handle exceptions using the try/except/finally clauses (§13.6) To raise exceptions using the raise statements (§13.7) To become familiar with Python’s built-in exception classes (§13.8) To access exception object in the handler (§13.8) To define custom exception classes (§13.9) To perform binary IO using the pickle module (§13.10) 3

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Open a File 4 How do you write data to a file and read the data back from a file? You need to create a file object that is associated with a physical file. This is called opening a file. The syntax for opening a file is as follows: file = open(filename, mode)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Write to a File 5 outfile = open("test.txt", "w") outfile.write("Welcome to Python") WriteDemoRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Testing File Existence 6 import os.path if os.path.isfile("Presidents.txt"): print("Presidents.txt exists")

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Read from a File 7 After a file is opened for reading data, you can use the read method to read a specified number of characters or all characters, the readline() method to read the next line, and the readlines() method to read all lines into a list. ReadDemoRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Append Data to a File 8 You can use the 'a' mode to open a file for appending data to an existing file. AppendDemoRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Writing/Reading Numeric Data 9 To write numbers, convert them into strings, and then use the write method to write them to a file. In order to read the numbers back correctly, you should separate the numbers with a whitespace character such as ' ', '\n'. WriteReadNumbersRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. File Dialogs 10 from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfilename filenameforReading = askopenfilename() print("You can read from from " + filenameforReading) filenameforWriting = asksaveasfilename() print("You can write data to " + filenameforWriting)

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. File Editor 11 FileEditorRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Problem: Counting Each Letter in a File 12 The problem is to write a program that prompts the user to enter a file and counts the number of occurrences of each letter in the file regardless of case. CountEachLetterRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Retrieving Data from the Web 13 Using Python, you can write simple code to read data from a Website. All you need to do is to open a URL link using the urlopen function as follows: infile = urllib.request.urlopen(' import urllib.request infile = urllib.request.urlopen(' print(infile.read().decode()) CountEachLetterURLRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Exception Handling 14 When you run the program in Listing 11.3 or Listing 11.4, what happens if the user enters a file or an URL that does not exist? The program would be aborted and raises an error. For example, if you run Listing 11.3 with an incorrect input, the program reports an IO error as shown below: c:\pybook\python CountEachLetter.py Enter a filename: newinput.txt Traceback (most recent call last): File "CountEachLetter.py", line 23, in main() File "CountEachLetter.py", line 4, in main Infile = open(filename, "r"> # Open the file IOError: [Errno 2] No such file or directory: 'newinput.txt'

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. The try... except Clause try: except : 15

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. The try... except Clause try: except :... except : except: else: finally: 16 TestException Run

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Raising Exceptions You learned how to write the code to handle exceptions in the preceding section. Where does an exception come from? How is an exception created? Exceptions are objects and objects are created from classes. An exception is raised from a function. When a function detects an error, it can create an object of an appropriate exception class and raise the object, using the following syntax: raise ExceptionClass("Something is wrong") 17 RaiseExceptionRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Processing Exceptions Using Exception Objects You can access the exception object in the except clause. 18 ProcessExceptionObject Run try except ExceptionType as ex:

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Defining Custom Exception Classes 19 TestCircleWithCustomException Run InvalidRadiusException

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Binary IO Using Pickling 20 To perform binary IO using pickling, open a file using the mode 'rb' or 'wb' for reading binary or writing binary and invoke pickle module’s dump and load functions to write and read data. BinaryIODemoRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Detecting End of File 21 If you don’t know how many objects are in the file, how do you read all the objects? You can repeatedly read an object using the load function until it throws an EOFError exception. When this exception is raised, catch it and process it to end the file reading process. DetectEndOfFileRun

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Case Study: Address Book 22 Now let us use object IO to create a useful project for storing and viewing an address book. The user interface of the program is shown below. The Add button stores a new address at the end of the file. The First, Next, Previous, and Last buttons retrieve the first, next, previous, and last addresses from the file, respectively. AddressBookRun