22
An Introduction To Software Development Using Python Spring Semester, 2014 Class #20: Files, Part 2

An Introduction To Python - Files, Part 2

Embed Size (px)

Citation preview

Page 1: An Introduction To Python - Files, Part 2

An Introduction To Software

Development Using Python

Spring Semester, 2014

Class #20:

Files, Part 2

Page 2: An Introduction To Python - Files, Part 2

Reading Lines From A File

• You have seen how to read a file one line at a time. However, there is a simpler way.

• Python can treat an input file as though it were a container of strings in which each line comprises an individual string. To read the lines of text from the file, you can iterate over the file object using a for loop.

• For example, the following loop reads all lines from a file and prints them:for line in infile :

print(line)

• At the beginning of each iteration, the loop variable line is assigned a string that contains the next line of text in the file. Within the body of the loop, you simply process the line of text. Here we print the line to the terminal.

Image Credit: www.clipartpanda.com

Page 3: An Introduction To Python - Files, Part 2

Problem With Files: Redo & \n

• There is one key difference between a file and a container, however. Once the file has been read, you cannot iterate over the file again without first closing and reopening the file.

• Remember, the print function prints its argument to the terminal and then starts a new line by printing a newline character.

• Because each line ends with a newline character, the second newline creates a blank line in the output.

• Generally, the newline character must be removed before the input string is used

Image Credit: www.clipartpanda.com

Page 4: An Introduction To Python - Files, Part 2

Getting Rid Of \n

• When the first line of the text file is read, the string line contains:s p a m \n

• To remove the newline character, apply the rstrip method to the string:line = line.rstrip()

which results in the new strings p a m

• By default, the rstrip method creates a new string in which all white space (blanks, tabs, and newlines) at the end of the string has been removed.

• For example, if there are two blank spaces following the word eggs in the second line of text

e g g s \n

• The rstrip method will remove not only the newline character but also the blank spaces:

e g g s Image Credit: www.clker.com

Page 5: An Introduction To Python - Files, Part 2

Reading Words

• Sometimes you may need to read the individual words from a text file.

• Because there is no method for reading a word from a file, you must first read a line and then split it into individual words.

• This can be done using the split method:wordList = line.split()

• The split method returns the list of substrings that results from splitting the string at each blank space

Image Credit: all-free-download.com

Page 6: An Introduction To Python - Files, Part 2

Trimming Strings

• The blank spaces are not part of the substrings. They only act as the delimiters for where the string will be split.

• Notice that the last word in the line contains a comma. If we only want to print the words contained in the file without punctuation marks, then we can strip those from the substrings using the rstripmethod:

word = word.rstrip(".,?!")

Image Credit: www.zazzle.com

Page 7: An Introduction To Python - Files, Part 2

The Split Method

• By default, the split method uses white space characters as the delimiter. You can alsosplit a string using a different delimiter.

• We can specify the colon as the delimiter to be used by the split method. Example:

substrings = line.split(":")

Image Credit: cliparts101.com

Page 8: An Introduction To Python - Files, Part 2

Reading Characters

• Instead of reading an entire line, you can read individual characters with the read method.

• The read method takes a single argument that specifies the number of characters to read. The method returns a string containing the characters.

• When supplied with an argument of 1,

char = inputFile.read(1)

the read method returns a string consisting of the next character in the file.

• Or, if the end of the file is reached, it returns an empty string "".

Image Credit: www.clipartpanda.com“Z”

Page 9: An Introduction To Python - Files, Part 2

Reading Records

• A text file can contain a collection of data records in which each record consists of multiple fields.

• For example, a file containing student data may consist of records composed of an identification number, full name, address, and class year.

• A file containing bank account transactions may contain records composed of the transaction date, description, and amount.

• When working with text files that contain data records, you generally have to read the entire record before you can process it:

For each record in the fileRead the entire record.Process the record.

Image Credit: imgarcade.com

Page 10: An Introduction To Python - Files, Part 2

Reading Records

• The organization or format of the records can vary, however, making some formats easier to read than others.

• How to build a record by reading multiple lines from a file:– The first fileld of the first record has to be obtained as the “priming read” in case the file

contains no records.

– Once inside the loop, the remaining fields of the record areread from the file. The newline character is stripped from the end of string fields, and strings containing numerical fields are converted to their appropriate type (e.g. int).

– At the end of the loop body, the first field of the next record is obtained as the “modification read”.

Image Credit: www.allthingskevyn.com

Page 11: An Introduction To Python - Files, Part 2

Exception Handling

• There are two aspects to dealing with program errors: detection and handling.

• For example, the open function can detect an attempt to read from a non-existent file. However, it cannot handle that error.

• A satisfactory way of handling the error might be to terminate the program, or to ask the user for another file name. The open function cannot choose between these alternatives. It needs to report the error to another part of the program

• In Python, exception handling provides a flexible mechanism for passing control from the point of error detection to a handler that can deal with the error. In the following sections, we will look into the details of this mechanism.

Image Credit: www.clipartsfree.net

Page 12: An Introduction To Python - Files, Part 2

Part of the Hierarchy of Exception Classes

Page 13: An Introduction To Python - Files, Part 2

Example: Overdrawing Your Banking Account

• When you detect an error condition, your job is really easy. You just raise an appropriate exception, and you are done.

• For example, suppose you try to withdraw too much money from your bank account.

if amount > balance :# Now what?

• First look for an appropriate exception. The Python library provides a number of standard exceptions to signal all sorts of exceptional conditions.

– Look around for an exception type that might describe your situation. How about the ArithmeticError exception? Is it an arithmetic error to have a negative balance? No,

– Python can deal with negative numbers. Is the amount to be withdrawn an illegal value? Indeed it is. It is just too large.

Image Credit: www.clipartpanda.com

Page 14: An Introduction To Python - Files, Part 2

Raising An Exception

• Is the amount to be withdrawn an illegal value? Indeed it is. It is just too large.

• Therefore, let’s raise a ValueError exception.if amount > balance :

raise ValueError("Amount exceeds balance")

• When you raise an exception, execution does not continue with the next statement but with an exception handler.

Page 15: An Introduction To Python - Files, Part 2

Handling Exceptions

• Every exception should be handled somewhere in your program.

• If an exception has no handler, an error message is printed, and your program terminates. Of course, such an unhandled exception is confusing to program users.

Image Credit: www.clipartpanda.com

Page 16: An Introduction To Python - Files, Part 2

Handling Exceptions

• You handle exceptions with the try/except statement.

• Place the statement into a location of your program that knows how to handle a particular exception.

• The try block contains one or more statements that may cause an exception of the kind that you are willing to handle.

• Each except clause contains the handler for an exception type.

Image Credit: www.clipartpanda.com

Page 17: An Introduction To Python - Files, Part 2

What Does All Of This Look Like?

Page 18: An Introduction To Python - Files, Part 2

The Finally Clause

Page 19: An Introduction To Python - Files, Part 2

The Finality Clause

• In a normal case, there will be no problem. When the try block is completed, thefinally clause is executed, and the file is closed. However, if an exception occurs, the finally clause is also executed before the exception is passed to its handler.

• Use the finally clause whenever you need to do some clean up, such as closing afile, to ensure that the clean up happens no matter how the method exits.

outfile = open(filename, "w")writeData(outfile)outfile.close() # May never get here.

outfile = open(filename, "w")try :

writeData(outfile)finally :

outfile.close()

Page 20: An Introduction To Python - Files, Part 2

What’s In Your Python Toolbox?

print() math strings I/O IF/Else elif While For

Lists And/Or/Not Functions Files Exception

Page 21: An Introduction To Python - Files, Part 2

What We Covered Today

1. Reading lines from a file

2. Reading words from a file

3. Reading characters from a file

4. Reading records from a file

5. Exceptions

Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/

Page 22: An Introduction To Python - Files, Part 2

What We’ll Be Covering Next Time

1. Sets

Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/