Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.

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

1 Exception-Handling Overview Exception: when something unforeseen happens and causes an error Exception handling – improves program clarity by removing.
Introduction to C Programming
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
1 Exception-Handling Overview Exception: when something unforeseen happens and causes an error Exception handling – improves program clarity by removing.
1 Exception-Handling Overview Exception: when something unforeseen happens and causes an error Exception handler catches a raised/thrown exception try.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Introduction to C Programming
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Exceptions COMPSCI 105 S Principles of Computer Science.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
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.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
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.
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.
Linux+ Guide to Linux Certification, Third Edition
If statements while loop for loop
Course A201: Introduction to Programming 12/9/2010.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
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.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Files Tutor: You will need ….
Python Let’s get started!.
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Programming Logic and Design Fourth Edition, Comprehensive Chapter 14 Event-Driven Programming with Graphical User Interfaces.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
CIT 590 Intro to Programming Files etc. Agenda Files Try catch except A module to read html off a remote website (only works sometimes)
Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
CIT 590 Intro to Programming Lecture 6. Vote in the doodle poll so we can use some fancy algorithm to pair you up You.
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”
Introduction to Computing Science and Programming I
Topic: File Input/Output (I/O)
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
Department of Computer Science,
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
I210 review.
ERRORS AND EXCEPTIONS Errors:
Fundamentals of Python: First Programs
Python Syntax Errors and Exceptions
Topics Introduction to File Input and Output
Bryan Burlingame 17 April 2019
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Dealing with Runtime Errors
Presentation transcript:

Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game

Objectives  So far we know how to get user’s input using raw_input(), and print out to the screen using print statements!  Now we are going to learn how to use files –Read from text files –Write to text files (permanent storage) –Need to open a file before using it, and close it when it is done  Read and write more complex data with files using cPickle module (optional!)  Intercept and handle errors during a program’s execution Guide to Programming with Python2

We are Talking about Plain Text Files  Plain text file: File made up of only ASCII characters  Easy to read strings from plain text files  Text files good choice for simple information –Easy to edit –Cross-platform –Human readable! Guide to Programming with Python3

Opening and Closing a Text File text_file = open("read_it.txt", "r") text_file.close()  Must open before read (or write); then you read from and/or write to the file by referring to the file object  Always close file when done reading or writing  Can open a file for reading, writing, or both Guide to Programming with Python4 1 st argument: filename 2 nd argument: access mode File object

File Access Modes Files can be opened for reading, writing, or both. Guide to Programming with Python5

Reading from a Text File oneletter = text_file.read(1) #read one character fiveletter = text_file.read(5)#read 5 characters whole_thing = text_file.read()#read the entire file  read() file object method –Argument: number of characters to be read; if not given, get the entire file –Return value: string  Each read() begins where the last ended  At end of file, read() returns empty string Guide to Programming with Python6

Reading a Line from a File text_file = open("read_it.txt", "r") line1 = text_file.readline() line2 = text_file.readline() line3 = text_file.readline()  readline() file object method –Returns the entire line if no value passed –Once read all of the characters of a line (including the newline), next line becomes current line text_file.readline(number_of_characters) # a little confusing Guide to Programming with Python7

Reading All Lines into a List text_file = open("read_it.txt", "r") lines = text_file.readlines() #lines is a list!  readlines() file object method –Reads text file into a list –Returns list of strings –Each line of file becomes a string element in list Compared to: read(), which reads the entire file into a string (instead of a list of strings) Guide to Programming with Python8

Looping Through a Text File >>> text_file = open("read_it.txt", "r") >>> for line in text_file: print line Line 1 This is line 2 That makes this line 3  Can iterate over open text file, one line at a time Guide to Programming with Python9

Two More Useful String’s Methods e.g., read_it.txt: Hunter 98 good Nathan 67 bad #The following lines for reading names and scores: text_file = open("read_it.txt", "r") for line in text_file: line = line.strip() (name, score) = line.split() str.split([sep[, maxsplit]]) -- Return a list of the words in the string, using sep as the delimiter string. If sep is not specified or None, any whitespace string is a separator '1<>2<>3'.split('<>') returns ['1', '2', '3']) str.strip([chars]) -- Return a copy of the string with the leading and trailing characters removed ' spacious '.strip() returns 'spacious' 10

Writing (a List of) Strings to a Text File text_file = open("write_it.txt", "w") text_file.write("Line 1\n") text_file.write("This is line 2\n") text_file.write("That makes this line 3\n”)  write() file object method writes new characters to file open for writing text_file = open("write_it.txt", "w") lines = ["Line 1\n", "This is line 2\n", "That makes this line 3\n"] text_file.writelines(lines)  writelines() file object method writes list of strings to a file Guide to Programming with Python11

Pickling/Unpickling Data to/from a File (Optional!)  Pickling: Storing complex objects (e.g., lists, dictionaries) in files  cPickle module to pickle and store more complex data in a file #pickle & write to file import cPickle variety = ["sweet", "hot", "dill"] pickle_file = open("pickles1.dat", "w") cPickle.dump(variety, pickle_file) #unpickle and read from a file pickle_file = open("pickles1.dat", "r") variety = cPickle.load(pickle_file) print variety Guide to Programming with Python12

Using a Shelf to Store/Get Pickled Data (Optional!)  shelf: An object written to a file that acts like a dictionary, providing random access to a group of objects (pickled) import shelve pickles = shelve.open("pickles2.dat”) pickles["variety"] = ["sweet", "hot", "dill"] pickles.sync() #sync() shelf method forces changes to be written to file for key in pickles.keys() print key, "-", pickles[key] #Shelf acts like a dictionary--Can retrieve pickled objects through key 13

Handling Exceptions >>> 1/0 Traceback (most recent call last): File " ", line 1, in -toplevel- 1/0 ZeroDivisionError: integer division or modulo by zero  Exception: An error that occurs during the execution of a program  Exception is raised and can be caught (or trapped) then handled  Unhandled, halts program and error message displayed Guide to Programming with Python14

Using a try Statement with an except Clause try: num = float(raw_input("Enter a number: ")) except: print "Something went wrong!"  try statement sections off code that could raise exception  Instead of raising exception, except block run  If no exception raised, except block skipped Guide to Programming with Python15

Specifying an Exception Type try: num = float(raw_input("\nEnter a number: ")) except(ValueError): print "That was not a number!“  Different types of errors raise different types of exceptions  except clause can specify exception types to handle  Attempt to convert "Hi!" to float raises ValueError exception  Good programming practice to specify exception types to handle each individual case  Avoid general, catch-all exception handling Guide to Programming with Python16

Selected Exception Types Table 7.5: Selected exception types Guide to Programming with Python17

Handling Multiple Exception Types for value in (None, "Hi!"): try: print "Attempting to convert", value, "–>", print float(value) except(TypeError, ValueError): print "Something went wrong!“  Can trap for multiple exception types  Can list different exception types in a single except clause  Code will catch either TypeError or ValueError exceptions Guide to Programming with Python18

Handling Multiple Exception Types (continued) for value in (None, "Hi!"): try: print "Attempting to convert", value, "–>", print float(value) except(TypeError): print "Can only convert string or number!" except(ValueError): print "Can only convert a string of digits!“  Another method to trap for multiple exception types is multiple except clauses after single try  Each except clause can offer specific code for each individual exception type Guide to Programming with Python19

Getting an Exception’s Argument try: num = float(raw_input("\nEnter a number: ")) except(ValueError), e: print "Not a number! Or as Python would say\n", e  Exception may have an argument, usually message describing exception  Get the argument if a variable is listed before the colon in except statement Guide to Programming with Python20

Adding an else Clause try: num = float(raw_input("\nEnter a number: ")) except(ValueError): print "That was not a number!" else: print "You entered the number", num  Can add single else clause after all except clauses  else block executes only if no exception is raised  num printed only if assignment statement in the try block raises no exception Guide to Programming with Python21 handle_it.py

Summary (Files)  How do you open a file? file = open(file_name, mode)  How do you close a file? file.close()  How do you read all the characters from a line in a file? the_string = file.readline()  How do you read all the lines from a file into a list? the_list = file.readlines()  How do you loop through a file? for aline in file:  How do you write text to a file? file.write(the_text)  How do you write a list of strings to a file? file.writelines(the_list) Guide to Programming with Python22

Summary (Exceptions)  What is an exception (in Python)? –an error that occurs during the execution of a program  How do you section off code that could raise an exception (and provide code to be run in case of an exception)? –try / except(SpecificException) / else  If an exception has an argument, what does it usually contain? –a message describing the exception  Within a try block, how can you execute code if no exception is raised? –else: Guide to Programming with Python23

Using Modules: os & sys  The ‘os’ module provides functions for interacting with the operating system –Ref: theory.co.uk/docs/pytut/OperatingSystemInterface.htmlhttp:// theory.co.uk/docs/pytut/OperatingSystemInterface.html – –os.getcwd() # Return the current working directory –os.chdir() #change the working directory –os.path.exists('/usr/local/bin/python') –os.path.isfile(‘test.txt’) –os.listdir(os.getcwd()) #get a list of the file in current directory  The ‘sys’ module: System-specific parameters and functions –Ref: –sys.argv # The list of command line arguments passed to a Python script –sys.exit([arg]) #exit from python 24