Object-Oriented Programming in Python Goldwasser and Letscher Chapter 8 Input, Output, and Files...

27
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 8 Input, Output, and Files Terry Scott University of Northern Colorado 2007 Prentice Hall

Transcript of Object-Oriented Programming in Python Goldwasser and Letscher Chapter 8 Input, Output, and Files...

Object-Oriented Programming in PythonGoldwasser and Letscher

Chapter 8Input, Output, and Files

Terry ScottUniversity of Northern Colorado

2007 Prentice Hall

2

Introduction: What is Covered in Chapter 8

• Standard Input and Output (I/O).

• Formatted I/O.

• File Operations.– Reading a file.– Writing a file.– Attempting to read a file when it doesn't exist.

• Case Studies.

3

Standard Input and Output

• standard input – get information from the keyboard.

• example with default value.

favoriteFruit = raw_input('What is your favorite fruit? ')

color = raw_input('Favorite color? (blue) ')

if not color:

color = 'blue'

4

Standard Input and Output (continued)

• Standard Output: example: comma outputs a space

print 'I like', favoritefruit, 'and the number',myAge

• another example: comma at end prevents new line

print 'I like', favoriteFruit,

print 'and the number', myAge

• example: unwanted space after team output

print team, ': ranked ', rank, 'of', total, 'teams'

5

Formatted Strings (continued)

• Unwanted space between team name and :

• to fix this use concatenation of strings (+ operator). Must convert numbers to strings

print team + ': ranked ' + str(rank) + ' of ' + str(total) + ' teams

6

Formatted Strings (continued)

• Can write previous statement using formatting strings like this.

print '%s: ranked %d of %d teams' % (team, rank, total)

• Format strings are:– %s is for strings

– %d is for integers

– %f is for floats. %.2f gives two decimal places.

• Page 274 gives examples

7

Working with Files

• Information stored in RAM goes away (is volatile) when the computer is shut off.

• Information stored on disk is non-volatile (does not go away when the computer is turned off).

• Writing to and reading from a file can help preserve information between different executions of a program.

8

Python File Type

• creating a new file instance is accomplished in the same way that a new list object is made.

fileObj = file(filename)

9

File OperationsSyntax Semantics

close() disconnect file from Python filevariable and saving file.

flush() flushes buffer of written characters.

read() returns a string with remaining contents of the file.

read(size) returns a string with size bytes remaining in file.

readline() returns string that contains next line in the file.

10

File Operations (continued)

Syntax Semantics

readlines() returns a list of strings of the remaining lines in the file.

write(s) writes s to the file. No newlines are added.

writelines(seq) writes the lines in seq to the file.

for line in f: iterates through the line f, one line at a time.

11

Reading from a File:Counting lines, words, and characters

version 1

filename = raw_input('What is the filename? ')source = file(filename)text = source.read() #read entire file as one stringnumchars = len(text)numwords = len(text.split())numlines = len(text.split('\n')

print numberlines, numwords, numcharssource.close()

12

Reading from a File:Counting lines, words, and characters

version 2filename = raw_input('What is the filename? ')source = file(filename)numlines = numwords = numcharacters = 0line = source.readline()while line: #read one line at a time. (non-null line is True)

numchars += len(line)numwords += len(line.split())numlines += 1line = source.readline()

print numlines, numwords, numcharssource.close()

13

Reading from a File:Counting lines, words, and characters

version 3filename = raw_input('What is the filename? ')source = file(filename)numlines = numwords = numcharacters = 0for line in source: #reads one line at a time until no more.

numchars += len(line)numwords += len(line.split())numlines += 1line = source.readline()

print numlines, numwords, numcharssource.close()

14

Writing to a File

• Creating a new file object that can be written to in Python with a file name of filename.

result = file(filename, 'w')• If the file with filename already exists then it will

be overwritten.• Only strings can be written to a file

pi = 3.14159

result.write(pi) #this is illegal

result.write(str(pi)) #this is legal

15

Writing to a File

• When is the information actually written to a file?

• File writing is time expensive so files may not be written immediately.

• A file can be forced to be written in two ways:– flush(): file written but not closed.– close(): file written and then closed.

16

Trying to Read a File That Doesn't Exist.

• What if opening file for reading and no file with that name exists? IOError – crashes program. To avoid this use an exception.

filename = raw_input('Enter filename: ')

try:

source = file(filename)

except IOError:

print 'Sorry, unable to open file', filename

17

File Utilities

# Prompt for filename until file is successfully opened.def fileReadRobust(): source = None while not source:

filename = raw_input('Input filename: ')try: source = file(filename)except IOError: print 'Sorry, unable to open file', filename

return source

18

File Utilities (continued)# Repeatedly prompt for filename until successfully # opening file with write access.def fileWriteRobust(defaultName): writable = None while not writeable:

prompt = 'Output filename [%s]?: ',%defaultName)filename = raw_input(prompt)if not filename: filename = defaultNametry: writeable = file(filename)except IOError: print 'Sorry, unable to write to file', filename

return writeable

19

Annotating a File# Making a copy of the file with line numbersfrom FileUtilities import fileReadRobust,fileWriteRobustprint 'This program annotates a file, by adding'print 'Line numbers to the left of each line.\n'source = fileReadRobjust()annotated = fileWriteRobust('annotated.txt')linenum = 1for line in source:

annotated.write('%4d $s' %(linenum, line)) linenum += 1

source.close()annotated.close()print 'The annotation is complete.'

20

Tallying Frequencies

• Used in statistical analysis.

• Used in breaking encryption codes.

• How do you do the analysis?

• Use if – elif statements: could be 26 choices if alphabet or perhaps 100 if digits and other punctuation is included.

• Better choice: use a list.

21

Tally Sheet Public Interface

22

Tallying Alphabetic Totalsfrom FileUtilities import fileReadRobust,

fileWriteRobustfrom TallySheet import TallySheetprint 'Counts frequency of letters – only count'print 'alphabetic characters.'sheet = TallySheet('A','Z')source = fileReadRobust()character = 'FAKE' #primes the loopwhile character: character = source.read(1) #read a single char.

if character.isalpha() sheet.increment(character.upper()) source.close()tallyfile = fileWriteRobust('frequencies.txt')sheet.writeTable(tallyfile)print 'The tally has been written.'

23

TallySheet Implementation

#A class for counting number of consecutive integer

#values or consecutive sequence of characters.

class TallySheet:

def __init__(self, minVal, maxVal):

self._minV = minVal

self._maxV = maxVal

maxIndex = self._toIndex(maxVal)

self._tallies = [0] * (maxIndex + 1)

24

Tally Implementation (continued)

def increment(self, val): ind = self._toIndex(val) if not 0 <= ind < len(self._tallies): raise ValueError('parameter '+str(val)+' out of range') self._tallies[ind] += 1

def getCount(self, val):ind = self._toIndex(val)if not 0 <= ind < len(self._tallies): raise ValueError('parameter '+ str(val)+

' out of range')return self._tallies[ind]

25

Tally Implementation (continued)

def getTotalCount(self): return sum(self._tallies)

def _toIndex(self,val): try: if isinstance(self._minV, str):

i = ord(val) – ord(self._minV) else: i = int(val – self._minV)

except TypeError: raise TypeError('parameter '+str(val)+

' of incorrect type') return i

26

Tally Implementation (continued)

def writeTable(self, outfile):

outfile.write('Value Count Percent \n')

outfile.write('----- ------ -------\n')

total = max(self.getTotalCount(), 1)

for ind in range(len(self._tallies)):

label = self._makeLabel(ind)

count = self._tallies[ind]

pct = 100.0 * count / total

outfile.write('%s %6d %6.2f\n' % (label, count, pct)

27

Tally Implementation (continued)

def _makeLabel(self, ind):

if isinstance(self._minV, int):

return ' %5d' % (ind + self._minV)

else:

return ' %s ' % chr(ind + ord(self._minV