Starting Out with Python - Chapter 6 - Files and Exceptions PDF

Summary

This document is a chapter from a Python textbook, focusing on file operations and exceptions. The chapter describes different types of files, how to open, use, and process them. Different methods and examples are shown in order to understand the material.

Full Transcript

Starting out with Python Fourth Edition Chapter 6 Files and Exceptions Reham Hamdy Abou-Zaid, 2024 Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions User Input Data The programs y...

Starting out with Python Fourth Edition Chapter 6 Files and Exceptions Reham Hamdy Abou-Zaid, 2024 Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions User Input Data The programs you have written so far require the user to reenter data each time the program runs, because data stored in RAM (referenced by variables) disappears once the program stops running. 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’s file system Saved data can be retrieved and used at a later time Writing Data on File “Writing data to”: saving data on a file Output file: a file that data is written to because the program stores output in it. Figure 6-1 Writing data to a file Reading Data From File “Reading data from”: process of retrieving data from a file Input file: a file from which data is read Figure 6-2 Reading data from a file Three steps when a program uses a file: 1. Open the file: creates a connection between the file and the program. 2. Process the file: data is either written to the file or read from the file. 3. Close the file: When the program is finished using the file, the file must be closed. Closing a file disconnects the file from the program Types of Files and File Access Methods In general, two types of files Text file: contains data that has been encoded as text, using a scheme such as ASCII or Unicode. Even if the file contains numbers, those numbers are stored in the file as a series of characters. As a result, the file may be opened and viewed in a text editor such as Notepad Binary file: contains data that has not been converted to text. The data that is stored in a binary file is intended only for a program to read. As a consequence, you cannot view the contents of a binary file with a text editor. Types of Files and File Access Methods Two ways to access data stored in file Sequential access: file read sequentially from beginning to end, can’t skip ahead. Similar to the way older cassette tape players work. If you want to listen to the last song on a cassette tape, you have to either fast-forward over all of the songs that come before it or listen to them. There is no way to jump directly to a specific song. Direct access: can jump directly to any piece of data in the file. This is similar to the way a CD player or an MP3 player works. You can jump directly to any song that you want to listen to. 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 Example:.jpg,.txt ,.docx 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 Filenames and File Objects Figure 6-4 A variable name references a file object that is associated with a file 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: Opening a File After this statement executes, the file named customers.txt will be opened, and the variable customer file will reference a file object that we can use to read data from the file. After this statement executes, the file named sales.txt will be created, and the variable sales file will reference a file object that we can use to write data to the file. 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 (r specifies that the string is a raw string) 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() Example: Writing Data to a File Let’s assume customer_file references a file object, and the file was opened for writing with the 'w' mode. Here is an example of how we would write the string ‘Charles Pace’ to the file: The following code shows another example: The following statement closes the file that is associated with customer_file: Example: Open File- Writing Data to a File – Close File Example: Open File- Writing Data to a File – Close File Contents of the file philosophers.txt Contents of philosophers.txt in Notepad 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 Reading Data From a File Line_read From a File Notice that a blank line is displayed after each line in the output. This is because each item that is read from the file ends with a newline character (\n) 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 Concatenating a Newline to a String Stripping a New line From a String This program uses the rstrip method to strip the \n from the strings that are read from the file before they are displayed on the screen. As a result, the extra blank lines do not appear in the output. 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 Appending Data to an Existing File For example, assume the file friends.txt contains the following names, each in a separate line: The following code opens the file and appends additional data to its existing contents. After this program runs, the file friends.txt will contain the following data: 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 Writing and Reading Numeric Data Writing and Reading Numeric Data 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 != '' Using Loops to Process Files Figure 6-17 General logic for detecting the end of a file Using Loops to Process Files 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 Using Python’s for Loop to Read Lines 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 Fields in A Records & Records in A File Process Records Fields in A Records & Records in A File Processing Records 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 Check examples pp(315-323) Exceptions Exception: error that occurs while a program is running Usually causes program to immediatly 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 Exceptions Many exceptions such as (ZeroDivisionError) can be prevented by careful coding Example: input validation Usually involve a simple decision construct Exceptions 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 Exceptions Exceptions 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 Exceptions 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 Exceptions (try suites) Exceptions (IOError) Exceptions (try suite & handler) 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 Handling Multiple Exceptions 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 ValueErroraserr: Can pass exception object variable to print function to display the default error message Displaying an Exception’s Default Error Message 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 The else Clause 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 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

Use Quizgecko on...
Browser
Browser