November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Computer Science 111 Fundamentals of Programming I Files.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
The University of Texas – Pan American
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Topics Introduction Hardware and Software How Computers Store Data
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
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.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Course A201: Introduction to Programming 12/9/2010.
Indexed and Relative 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.
Built-in Data Structures in Python An Introduction.
Functions Chapter 4 Python for Informatics: Exploring Information
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
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.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Introduction to Files in VB Chapter 9.1, 9.3. Overview u Data Files  random access  sequential u Working with sequential files  open, read, write,
PC204 Lecture 5 Conrad Huang Genentech Hall, N453A
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
Fundamentals of Python: First Programs
Files and Exceptions: The Trivia Challenge Game
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.
Lecture 4 Python Basics Part 3.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Binary Files.
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Python’s Errors and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
Topics Introduction Hardware and Software How Computers Store Data
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Topics Sequences Introduction to Lists List Slicing
Python Syntax Errors and Exceptions
Topics Introduction to File Input and Output
CPS120: Introduction to Computer Science
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
By Ryan Christen Errors and Exceptions.
Topics Sequences Introduction to Lists List Slicing
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Introduction to Computer Science
Introduction to Computer Science
Presentation transcript:

November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department of Computer Science Kent State University

November 15, 2005ICP: Chapter 7: Files and Exceptions 2 Contents Read from text files Write to text files Read and write complex data with files File examples Exceptions and error handling Exception and error handling examples

November 15, 2005ICP: Chapter 7: Files and Exceptions 3 Trivia Challenge Game Example: Trivia Challenge ProgramTrivia Challenge Program Data File: trivia.txttrivia.txt

November 15, 2005ICP: Chapter 7: Files and Exceptions 4 Reading From Text Files Secondary storage is the computer’s hardware unit for the long term storage of data. Hard disks are the most popular, but tapes, floppy disks, CF cards, and USB drives are other hardware devices for storing data persistently. A file is a sequence of characters stored on a disk drive. Files have a name and an optional file extension.

November 15, 2005ICP: Chapter 7: Files and Exceptions 5 Reading From Text Files Opening and closing a text file –Files have to be opened before a program can read (write) data from it –Syntax any_file = open( “data.dat”, “r” ) –Files also have to be closed when a program is finished with it –Syntax any_file.close()

November 15, 2005ICP: Chapter 7: Files and Exceptions 6 Reading From Text Files Opening and closing a text file –The file subdirectory path may have to be included in the file name any_file = open( “c:\ICP10061\exams\test1.txt”, “r” ) –The “r” is called the “access mode” r is for reading –if the file does not exist, an error is raised w is for writing –If the file exists, the contents are overwritten. If the file does not exist, it will be created a is for appending –If the file exists new data is appended to the end of the file. If the file does not exist, it will be created others listed in the text book

November 15, 2005ICP: Chapter 7: Files and Exceptions 7 Reading From Text Files Reading characters from a text file –There are several functions and methods for reading data from a file –The read() method allows a program to read a specified number of characters from a file and returns them as a string –Example any_file = open( “test.txt”, “r” ) print any_file.read(5) print any_file.read(4) any_file.close() –Python remembers where the file last read data by using a “file pointer” or “bookmark”

November 15, 2005ICP: Chapter 7: Files and Exceptions 8 Reading From Text Files Reading characters from a text file –All files have a “end of file” indicator (EOF) that signals to your program that there is no more data to read in a file –Trying to read past the end of the file will return an empty string –Example any_file = open( “test.txt”, “r” ) all_the_data = any_file.read() any_file.close()

November 15, 2005ICP: Chapter 7: Files and Exceptions 9 Reading From Text Files Reading characters from a line –Text files are often line oriented and your program may have to read and process one line at a time –The method read_line() is used to read characters from the current line only –Example anystring = any_file.readline(1) anystring = any_file.readline(5) anystring = any_file.readline()

November 15, 2005ICP: Chapter 7: Files and Exceptions 10 Reading From Text Files Reading all lines into a list –Another way to work with lines from a file is to read each line (string) into a list –The method read_lines() is used to read all the lines from a text file and store them into a list of lines (strings) –Example any_list = any_file.readlines()

November 15, 2005ICP: Chapter 7: Files and Exceptions 11 Reading From Text Files Looping through a text files –Text files are a type of sequence delimited by lines –Python programs can also read and process lines from text files by using iteration –Example for line in any_file: print line

November 15, 2005ICP: Chapter 7: Files and Exceptions 12 Reading From Text Files Example: Read It ProgramRead It Program Data File: read_it.txtread_it.txt

November 15, 2005ICP: Chapter 7: Files and Exceptions 13 Writing To A Text File Program must also be able to write data to files for other programs (or humans) to read Many text files are created (written to) automatically and as needed –Automatic creation of web pages –Database and program log files

November 15, 2005ICP: Chapter 7: Files and Exceptions 14 Writing To A Text File Writing strings to a file –There are several functions for writing data to a file –To write a single string to a text file use the write() method –Example any_file.write(“This is a test…\n”) any_file.write(“This is only a test\n” ) Note both strings could have been concatenated together into one string and have the same result using one write statement

November 15, 2005ICP: Chapter 7: Files and Exceptions 15 Writing To A Text File Writing a list of strings to a file –The writelines() method is the complement function to readlines() –It takes a list of strings and prints them to a file –Example any_file.writelines( any_list ) The newline characters must be embedded in each string for proper formatting (as needed)

November 15, 2005ICP: Chapter 7: Files and Exceptions 16 Writing To A Text File Example: Write It ProgramWrite It Program

November 15, 2005ICP: Chapter 7: Files and Exceptions 17 Storing Complex Data in Files Text files are convenient because humans can read and manipulate the data (strings) Reading and writing more complex data structures such as dictionaries may require more parsing on the part of the programmer Python provides a method of storing complex data using “pickling” which is a form of “serialization”

November 15, 2005ICP: Chapter 7: Files and Exceptions 18 Storing Complex Data in Files Pickling data and writing it to a file –To use the pickling functions your program must include the cPickle module import cPickle –Next open a file exactly the same way for text files car_file = open( “cars.dat”, “w” ) –Store your data by “dumping it” car_list = [“Chevy”, “Ford”, “Dodge”, “V W”, “Honda”, “Toyota”] cPickle.dump( car_list, car_file ) –Close the file car_file.close()

November 15, 2005ICP: Chapter 7: Files and Exceptions 19 Storing Complex Data in Files Reading data from a file and unpickling it –Open the data (pickle) file –Read the information using the load() method car_list = cPickle.load( car_file ) –Close the file

November 15, 2005ICP: Chapter 7: Files and Exceptions 20 Storing Complex Data in Files Using a shelf to store pickled data –A shelf can be thought of as a dictionary in a disk file –When you add key/value pairs to the shelf (dictionary) they are written to disk –Periodically the program must use the sync() method to copy the shelf changes to disk

November 15, 2005ICP: Chapter 7: Files and Exceptions 21 Storing Complex Data in Files Using a shelf to store pickled data –To use a shelf, the program must import shelve (note the name change!!!) import shelve –Next open a shelve file stuff = shelve.open( “data.dat” ) –Write data to the shelve stuff[‘cars’] = [‘Chevy’, ‘Ford’, ‘Dodge’] –Synchronize the data stuff.sync()

November 15, 2005ICP: Chapter 7: Files and Exceptions 22 Storing Complex Data in Files Using a shelf to retrieve pickled data –To read information out of the shelf treat it as a dictionary and supply a key for key in stuff.keys(): print key, stuff[key]

November 15, 2005ICP: Chapter 7: Files and Exceptions 23 Storing Complex Data in Files Example: Pickle It ProgramPickle It Program

November 15, 2005ICP: Chapter 7: Files and Exceptions 24 Handling Exceptions When Python (or any programming language) has an error, it stops the current execution and displays an error message “It raises an exception” Example: >>> 1/0 Traceback (most recent call last): File " ", line 1, in -toplevel- 1/0 ZeroDivisionError: integer division or modulo by zero

November 15, 2005ICP: Chapter 7: Files and Exceptions 25 Handling Exceptions Example: Handle It ProgramHandle It Program

November 15, 2005ICP: Chapter 7: Files and Exceptions 26 Handling Exceptions Using a try statement with an except clause –The most basic way to “handle” (or trap) an exception is to use the Python “try” and “except” clause –Example try: num = int( raw_input( “Enter a number” )) except: print “Something went wrong”

November 15, 2005ICP: Chapter 7: Files and Exceptions 27 Handling Exceptions Specifying an exception type –There are different type of exceptions IOError –Raised when an I/O operation fails, such as opening a non-existent file for reading IndexError –Raised when a sequence is indexed with a number out of range KeyError –Raised when a dictionary key is not found NameError –Raised when a name of variable or function is not found SyntaxError –Raised when a syntax error is found TypeError –Raised when a built-in operation or function is applied to an object with the wrong type ValueError –Raised when a built-in operation or function received an argument that has the right type but inappropriate value ZeroDivisionError –Raised when the second argument of a division or modulo operation is zero

November 15, 2005ICP: Chapter 7: Files and Exceptions 28 Handling Exceptions Specifying an exception type –Example try: num = int( raw_input( “Enter a number” )) except(ValueError): print “Something went wrong” –The print statement is only executed if the ValueError exception is raised

November 15, 2005ICP: Chapter 7: Files and Exceptions 29 Handling Exceptions When should you trap exceptions? –Any point of external interaction with your program Opening a file for reading Converting data from an outside source such as a user –If you do not know what exception to trap, test it in interactive mode with Python

November 15, 2005ICP: Chapter 7: Files and Exceptions 30 Handling Exceptions Handling multiple exception types –The except clauses can trap multiple types of exceptions –Example: for value in (None, “Hello”): try: print “Attempting to convert”, value, “->”, print float( value ) except(TypeError, ValueError): print “An error occurred”

November 15, 2005ICP: Chapter 7: Files and Exceptions 31 Handling Exceptions Handling multiple exception types –Example: for value in (None, “Hello”): try: print “Attempting to convert”, value, “->”, print float( value ) except(TypeError): print “Can only convert a string or a number” except(ValueError): print “Problem converting a string of digits”

November 15, 2005ICP: Chapter 7: Files and Exceptions 32 Handling Exceptions Getting an exception’s argument –Python allows the program to get the actual error message…(useful for debugging) –Example: try: num = int( raw_input( “Enter a number” )) except(ValueError), e: print “Data entered was not a number”, e

November 15, 2005ICP: Chapter 7: Files and Exceptions 33 Handling Exceptions Adding an else clause –Example: try: num = int( raw_input( “Enter a number” )) except(ValueError), e: print “Data entered was not a number”, e else: print “The value of num is”, num

November 15, 2005ICP: Chapter 7: Files and Exceptions 34 Trivia Challenge Game (Again) Example: Trivia Challenge ProgramTrivia Challenge Program Data File: trivia.txttrivia.txt Data file format