Difference between revisions of "CSC111 Lab 9 2014"

From dftwiki3
Jump to: navigation, search
(Catching Exceptions)
 
(46 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 23:40, 1 April 2014 (EDT)
 
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 23:40, 1 April 2014 (EDT)
 
----
 
----
 +
<br />
 +
<bluebox>This lab deals with text files in Python, also referred to as '''File Input/Output''' or '''File I/O'''.  You will write text, read text, write numbers, read numbers, and append to logs, all this with text files.
 +
</bluebox>
 +
<br />
 +
<br />
 +
<br />
 +
 +
 +
<br />
 +
<br />
  
 
=Reading and Writing Text Files=
 
=Reading and Writing Text Files=
 
+
<br />
 
==Write Example==
 
==Write Example==
 
<br />
 
<br />
Line 16: Line 26:
 
</source>
 
</source>
 
<br />
 
<br />
==Read Example==
+
==Read Examples==
 +
<br />
 +
===Print all the lines inside a File===
 +
<br />
 +
<source lang="python">
 +
file = open( "college.txt", "r" )
 +
for line in file:
 +
    print( line.strip() )
 +
file.close()
 +
</source>
 +
<br />
 +
;Output
 +
 +
Smith College
 +
1 Elm st., Northampton, MA 01063
 +
 +
<br />
 +
===Read the file as one whole string===
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
 
# read the same file back and print all the lines
 
# read the same file back and print all the lines
 
file = open( "college.txt", "r" )
 
file = open( "college.txt", "r" )
for line in file:
+
allLines = file.readlines()  # allLines is a list of strings, each line a separate string
  print( "line =", line.strip() )
 
 
file.close()
 
file.close()
 +
 +
oneString = "" . join( allLines )
 +
print( repr( oneString ) )  # repr() function makes special characters visible
 +
print( oneString )      # print it normally
 
</source>
 
</source>
 
<br />
 
<br />
 +
;Output
 +
 +
'Smith College\n1 Elm st., Northampton, MA 01063\n'
 +
Smith College
 +
1 Elm st., Northampton, MA 01063
 +
 +
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<!-- ----------------------------------------------------------------------------------------------- -->
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
==Exercise==
 +
|}
 +
[[Image:QuestionMark9.jpg|right|120px]]
 +
<br />
 +
* Try each of these examples above.
 +
 +
<br /><br />
 +
<br />
 +
<br /><br />
 +
<br />
 +
<br /><br />
 +
<br />
 +
 
=Writing Text to File and Reading it Back=
 
=Writing Text to File and Reading it Back=
 
<br />
 
<br />
Line 36: Line 95:
 
|}
 
|}
 
[[Image:QuestionMark1.jpg|right|120px]]
 
[[Image:QuestionMark1.jpg|right|120px]]
 +
<br />
 
* Use the example above and write a program that writes the string '''text''' defined below to a file named '''poem.txt''' in the same folder (directory) where your program is located.
 
* Use the example above and write a program that writes the string '''text''' defined below to a file named '''poem.txt''' in the same folder (directory) where your program is located.
 
+
<br />
 
:<source lang="python">
 
:<source lang="python">
 
text = """An Evening by Gwendolyn Brooks
 
text = """An Evening by Gwendolyn Brooks
Line 52: Line 112:
 
</source>
 
</source>
 
<br />
 
<br />
* Once the program terminates, open the file with '''TextEdit''' if working on a Mac, or with '''Notepad''' if working on Windows.  Verify that the file exists and that it contains the poem.
+
* Once the program terminates, open the file with '''TextEdit''' if working on a Mac, or with '''Notepad''' if working on Windows (you can double-click it in Windows Explorer).  Verify that the file exists and that it contains the poem.  If you are ambitious,  you may want to use the Console or the Terminal to locate the file the way we did in class, and display its contents on the screen using '''type''' (Windows) or '''cat''' (Mac).
 +
<br />
 +
* Put the code that writes the poem to file in a function called '''writeTextFile( fileName, text )''', where ''fileName'' is a parameter that will receive the name of the file, and ''text'' the name of a variable that will get the string to write to file.  The function should 1) open the file for writing, 2) write text to the file, and 3) close the file.
  
* Put the code that writes the poem to file in a function called '''writeTextFile( fileName, text )''', where ''fileName'' is the name of the file, and ''text'' the name of the variable.  The function should 1) open the file for writing, 2) write text to the file, and 3) close the file.
+
:Verify that your function works by deleting '''poem.txt''' and then running your new program.  If you function is written correctly, it will have recreated the '''poem.txt''' file with the same contents as before.
Verify that your function works by deleting '''poem.txt''' and then running your new program.  If you function is written correctly, it will have recreated the '''poem.txt''' file with the same contents as before.
+
<br /><br /><br /><br /><br /><br />
<br />
 
 
<!-- ----------------------------------------------------------------------------------------------- -->
 
<!-- ----------------------------------------------------------------------------------------------- -->
 
{| style="width:100%; background:silver"
 
{| style="width:100%; background:silver"
Line 66: Line 127:
 
[[Image:QuestionMark2.jpg|right|120px]]
 
[[Image:QuestionMark2.jpg|right|120px]]
  
* Add some code to your program that will read the file just created and print its contents (all the lines) on the screen.
+
* Get some inspiration from the "Read Examples" section above, and add some code to your program that will read the file just created and print its contents (all the lines) on the screen.  (Basically, add a ''file.open()'' statement, a loop to read and print the lines, and a file.close(), and you're done.)
 +
 
 +
* When this works, replace your code by a call to a function  called '''readTextFile()''' that will open the file, get its contents as a long string (once again, go back to the "Read Examples" section above to see how to do that).  The function at the end will use a '''return''' statement to return a long string that is equal to the full contents of the file.  
  
* When this works, put this new code into a function called '''readTextFile()''' that is given just the file name (''fileName'') and that returns a long string that is equal to the contents of the file.  Here is an example of how your program will use your new function to read the file and display the string:
+
Here is an example of how your program will use your new function to read the file and display the string:
  
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
 
         text = readTextFile(  "poem.txt" )
 
         text = readTextFile(  "poem.txt" )
         print( text )
+
         for line in text.split( "\n" ):
 +
            print( line )
 
</source>
 
</source>
 
<br />
 
<br />
  
 
=Writing Numbers to File and Reading them Back=
 
=Writing Numbers to File and Reading them Back=
 +
<br />
 +
The concept of writing a list of numbers to a text file is simple, and illustrated in the diagram below:
 +
 +
[ 1, 2, 3, 5, 10 ]
 +
&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;V
 +
[ '1', '2', '3', '5', '10' ]
 +
&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;V
 +
  '1\n2\n3\n5\n10\n'      ==(write)==>  text-file
  
 +
The concept of reading a list of numbers from a text file is simple as well, and illustrated in the diagram below:
 +
 +
  '1\n2\n3\n5\n10\n' &nbsp;&nbsp;&nbsp;<==(read)== &nbsp;&nbsp;&nbsp;text-file
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;V
 +
[ '1', '2', '3', '5', '10' ]
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;V
 +
[ 1, 2, 3, 5, 10 ]
 +
 +
 +
 
 +
   
 
<br />
 
<br />
 
Same idea: you write a function that takes a list of numbers and writes them to file, one per line.  Then you write a function that reads the numbers back, prints them, and computes their sum.  This last part is very important, because to text files contain text, or strings, and when you read that back into variables that are supposed to contain numbers, you must transform the strings into numbers.
 
Same idea: you write a function that takes a list of numbers and writes them to file, one per line.  Then you write a function that reads the numbers back, prints them, and computes their sum.  This last part is very important, because to text files contain text, or strings, and when you read that back into variables that are supposed to contain numbers, you must transform the strings into numbers.
Line 100: Line 191:
 
print( "Sum = ", sum( newNumbers ) )
 
print( "Sum = ", sum( newNumbers ) )
 
</source>
 
</source>
 +
<br />
 +
 +
;Hints
 +
:1) Text files contain only strings of characters.  To store numbers in a file you have to write the number as a string.  A good way to transform an integer into a one-line string is with  <tt>"%d\n" % x </tt>, where x is the integer in question.
 +
:2) When reading the file of integers, just read the file and display the lines in it as text.  Then little by little transform each line into an int.  Then when that works, figure out how to add the ints to a list, one at a time.
 +
 +
<br />
 
<br />
 
<br />
 
=Creating a Log =
 
=Creating a Log =
Line 171: Line 269:
 
[[Image:QuestionMark5.jpg|right|120px]]
 
[[Image:QuestionMark5.jpg|right|120px]]
 
<br />
 
<br />
* Create a new function called '''log( fileName, line )''' that adds a new line to a log file.  This function will open the log, append the list to it, and close it.  Using it will make our original discussion function much simpler:
+
* Create a new function called '''log( line )''' that adds a new line to the log file.  This function will assume the log file name is '''log.txt''', open the log, append the line to it, and close it.  Using it will make our original discussion function much simpler:
  
 
<br />
 
<br />
Line 179: Line 277:
 
     canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
 
     canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
 
     print( "Hello!" )
 
     print( "Hello!" )
     log( "log.txt", "Hello!" )
+
     log( "Hello!" )
 
     while True:
 
     while True:
 
           answer = input( "> " ).strip()
 
           answer = input( "> " ).strip()
           log( "log.txt", answer )
+
           log( answer )
 
           if answer.lower() in [ "bye", "ciao", "later" ]:
 
           if answer.lower() in [ "bye", "ciao", "later" ]:
 
                 break
 
                 break
 
           response = choice( canned )
 
           response = choice( canned )
 
           print( response )
 
           print( response )
           log( "log.txt", response )
+
           log( response )
 
     print( "Good bye!" )
 
     print( "Good bye!" )
     log( "log.txt", "Good bye!" )
+
     log( "Good bye!" )
 
</source>
 
</source>
 
<br />
 
<br />
Line 198: Line 296:
 
|
 
|
  
==Challenge 6==
+
==Challenge 6 ==
 
|}
 
|}
 
[[Image:QuestionMark6.jpg|right|120px]]
 
[[Image:QuestionMark6.jpg|right|120px]]
Line 210: Line 308:
 
<br />
 
<br />
 
<br />
 
<br />
 +
 +
=Submission=
 +
<br />
 +
Submit the program (which you should name '''lab9.py''') to this URL: [http://cs.smith.edu/~thiebaut/111b/submitL9.php  http://cs.smith.edu/~thiebaut/111b/submitL9.php]
 +
<br />
 +
<br />
 +
<br />
 +
<!--
 
=Catching Exceptions=
 
=Catching Exceptions=
 
<br />
 
<br />
Line 255: Line 361:
 
<br />
 
<br />
 
<br />
 
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
==Challenge of the Day==
 +
|}
 +
[[Image:QuestionMark8.jpg|right|120px]]
 +
<br />
 +
Add a new function to your program that will write the following lines of text to a text file.  You may call the file '''lab9data.txt'''.
 +
<br />
 +
<source lang="text">
 +
index name    cash  age  #-fans
 +
1    Doc      5.50  101  100
 +
2    Dopey    5.60    78  150
 +
3    Bashful  6.00    99  500
 +
4    Grumpy    4.80  100  99
 +
5    Sneezy    7.00    NA  876
 +
6    Sleepy    9.00    83  10
 +
7    Happy    ---    85  1,000,001
 +
</source>
 +
<br />
 +
Add another function designed to read text with the format shown above.  You can start your function with this very non-robust code:
 +
<br />
 +
<source lang="python">
 +
def readLab9Data( fileName ):
 +
    file = open( fileName, "r" )
 +
 +
    L = []
 +
    for line in file:
 +
      words = line.split( )
 +
     
 +
      index = int( words[0] )
 +
      name = words[1]
 +
      cash = float( words[2] )
 +
      age = int( words[3] )
 +
      fans = int( words[4] )
 +
      L.append( (name, cash, age, fans ) )
 +
 +
    file.close()
 +
    print( "L = ", L )
 +
</source>
 +
 +
<br />
 +
When you run this code you will right away get errors.  They are generated by the fact that some fields in the file are words when your program expects numbers. 
 +
 +
Make your function robust and add more code to your function so that it can read the file without error (make sure it works if the file name is misspelled!)
 +
 +
When your function works fine, make it  output the names of
 +
## the richest dwarf
 +
## the oldest dwarf
 +
## the most popular dwarf
 +
 +
Use as few if-statements as possible! 
 +
<br />
 +
Please show me your solution when you are done!
 +
<br />
 +
;Hints
 +
: Write your code as if the file was correctly formatted, then as you test it and generate exceptions, add '''try/catch''' statements to protect your code.
 +
: Your program should be able to recover if the user types the wrong file name!
 +
: List comprehension can be a powerful tool to modify a list of tuples, as follows.
 
<br />
 
<br />
 +
<source lang="python">
 +
    # a list with 2 Disney dwarves
 +
    L = [ ( "Doc", 5.5, 101, 100 ), ("Dopey", 5.6, 78, 150 ) ]
 +
 +
    # compact it into a new list with pairs of cash, name values
 +
    L2 = [ (cash, name) for name, cash, age, fans in L ]
 +
 +
    # sort it by cash amount
 +
    L2.sort()
 +
 +
    # get first dwarf in sorted list
 +
    cash, name = L2[0]
 +
 +
    # print its name and amount of cash
 +
    print( cash, name )
 +
</source>
 
<br />
 
<br />
 +
-->
 +
<br />
 +
<onlydft>
 +
<source lang="python">
 +
# CSC111 lab9 solution program
 +
 +
# challenge 1
 +
def writeTextFile( fileName, poemText ):
 +
    file = open( fileName, 'w' )
 +
    file.write( poemText )
 +
    file.close()
 +
 +
def challenge1():
 +
    text = """An Evening by Gwendolyn Brooks
 +
 +
A sunset's mounded cloud;
 +
A diamond evening-star;
 +
Sad blue hills afar;
 +
Love in his shroud.
 +
 +
Scarcely a tear to shed;
 +
Hardly a word to say;
 +
The end of a summer day;
 +
Sweet Love dead."""
 +
    writeTextFile( "poem.txt", text )
 +
 +
# challenge 2
 +
def readTextFile( fileName ):
 +
    file = open( fileName, "r" )
 +
    text = ""
 +
    for line in file:
 +
        text = text + line
 +
    file.close()
 +
    return text
 +
 +
def challenge2():
 +
    text = readTextFile( "poem.txt" )
 +
    for line in text.split("\n" ):
 +
        print( line )
 +
 +
 +
# reading and writing numbers
 +
def writeIntFile( fileName, list ):
 +
    file = open( fileName, "w" )
 +
    for x in list:
 +
        file.write( "%d\n" % x )
 +
    file.close()
 +
 +
def readIntFile( fileName ):
 +
    file = open( fileName, "r" )
 +
    list = []
 +
    for line in file:
 +
        line = line.strip()
 +
        x = int( line )
 +
        list.append( x )
 +
    return list
 +
   
 +
def playingWithNumbers():
 +
    numbers = [ 1, 2, 10, 100, 50, 7 ]
 +
    # write the list to file, one number per line
 +
    writeIntFile( "numbers.txt", numbers )
 +
 +
    # read the file of ints, and return it as a list of ints.
 +
    newNumbers = readIntFile( "numbers.txt" )
 +
 +
    # print the list of ints and their sum (should be 170)
 +
    for x in newNumbers:
 +
        print( x )
 +
 +
    print( "Sum = ", sum( newNumbers ) )
 +
 +
 +
#--- LOG ---
 +
from random import choice
 +
def discussion1():
 +
    print( "\n\nDiscussion 1\n\n" )
 +
    log = open( "log.txt", "w" )
 +
    canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
 +
    print( "Hello!" )
 +
    log.write( "Hello!\n" )
 +
    while True:
 +
          answer = input( "> " ).strip()
 +
          log.write( "> " + answer + "\n" )
 +
          if answer.lower() in [ "bye", "ciao", "later" ]:
 +
                break
 +
          reply = choice( canned )
 +
          print( reply )
 +
          log.write( reply + "\n" )
 +
         
 +
    print( "Good bye!" )
 +
    log.write( "Good bye!\n\n" )
 +
    log.close()
 +
 +
def log( text ):
 +
    file = open( "log.txt", "a" )
 +
    file.write( text + "\n" )
 +
    file.close()
 +
 +
def discussion2():
 +
    print( "\n\nDiscussion 2\n\n" )
 +
    canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
 +
    print( "Hello!" )
 +
    log( "Hello!" )
 +
    while True:
 +
          answer = input( "> " ).strip()
 +
          log( "> " + answer )
 +
          if answer.lower() in [ "bye", "ciao", "later" ]:
 +
                break
 +
          reply = choice( canned )
 +
          print( reply )
 +
          log( reply )
 +
         
 +
    print( "Good bye!" )
 +
    log( "Good bye!\n" )
 +
 +
# Challenge of the Day
 +
def createLab9Data():
 +
    file = open( "lab9data.txt", "w" )
 +
    file.write( """index name    cash  age  #-fans
 +
1    Doc      5.50  101  100
 +
2    Dopey    5.60    78  150
 +
3    Bashful  6.00    99  500
 +
4    Grumpy    4.80  100  99
 +
5    Sneezy    7.00    NA  876
 +
6    Sleepy    9.00    83  10
 +
7    Happy    ---    85  1,000,001\n""" )
 +
    file.close()
 +
 +
def catchingExceptions1( fileName ):
 +
    file = open( fileName, "r" )
 +
 +
    L = []
 +
    for line in file:
 +
      words = line.split( )
 +
     
 +
      index = int( words[0] )
 +
      name = words[1]
 +
      cash = float( words[2] )
 +
      age = int( words[3] )
 +
      fans = int( words[4] )
 +
      L.append( (name, cash, age, fans ) )
 +
 +
    print( "L = ", L )
 +
             
 +
def catchingExceptions2():
 +
    try:             
 +
      file = open( "lab9data.txt", "r" )
 +
    except IOError:
 +
      print( "Error opening hw9data.txt" )
 +
      return
 +
 +
    L = []
 +
    for line in file:
 +
      print( line )
 +
      words = line.split( )
 +
      try:
 +
          index = int( words[0] )
 +
      except ValueError:
 +
          continue # must be first line
 +
 +
      name = words[1]
 +
      try:
 +
          cash = float( words[2] )
 +
      except ValueError:
 +
          cash = 0
 +
      try:
 +
          age = int( words[3] )
 +
      except ValueError:
 +
          age = 0
 +
      try:
 +
          fans = int( words[4] )
 +
      except ValueError:
 +
          fans = int( words[4].replace( ',', '' ) )
 +
      L.append( (name, cash, age, fans ) )
 +
 +
    L1 = [ (cash, name) for name, cash, age, fans in L ]
 +
    L1.sort()
 +
    L1.reverse()
 +
    cash, richest = L1[0]
 +
    print( "richest dwarf is", richest, " with ", cash )
 +
 +
    L2 = [ (age, name ) for name, cash, age, fans in L ]
 +
    L2.sort()
 +
    L2.reverse()
 +
    age, oldest = L2[0]
 +
    print( "oldest is ", oldest, " at age ", age )
 +
 +
   
 +
def main():
 +
    #challenge1()
 +
    #challenge2()
 +
    #playingWithNumbers()
 +
    #discussion1()
 +
    #discussion2()
 +
    createLab9Data()
 +
    catchingExceptions2(  )
 +
main()
 +
 +
</source>
 +
</onlydft>
 
<br />
 
<br />
 
<br />
 
<br />
 
<br />
 
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 
[[Category:CSC111]][[Category:Python]][[Category:Lab]]
 
[[Category:CSC111]][[Category:Python]][[Category:Lab]]

Latest revision as of 08:11, 4 April 2014

--D. Thiebaut (talk) 23:40, 1 April 2014 (EDT)



This lab deals with text files in Python, also referred to as File Input/Output or File I/O. You will write text, read text, write numbers, read numbers, and append to logs, all this with text files.







Reading and Writing Text Files


Write Example


# write some variables to file
name = "Smith College"
address = "1 Elm st., Northampton, MA 01063"
file = open( "college.txt", "w" )
file.write( "%s\n" % name )
file.write( "%s\n" % address )
file.close()


Read Examples


Print all the lines inside a File


file = open( "college.txt", "r" )
for line in file:
    print( line.strip() )
file.close()


Output
Smith College
1 Elm st., Northampton, MA 01063


Read the file as one whole string


# read the same file back and print all the lines
file = open( "college.txt", "r" )
allLines = file.readlines()  # allLines is a list of strings, each line a separate string
file.close()

oneString = "" . join( allLines )
print( repr( oneString ) )  # repr() function makes special characters visible
print( oneString )       # print it normally


Output
'Smith College\n1 Elm st., Northampton, MA 01063\n'
Smith College
1 Elm st., Northampton, MA 01063






Exercise

QuestionMark9.jpg


  • Try each of these examples above.










Writing Text to File and Reading it Back


Challenge 1

QuestionMark1.jpg


  • Use the example above and write a program that writes the string text defined below to a file named poem.txt in the same folder (directory) where your program is located.


text = """An Evening by Gwendolyn Brooks

A sunset's mounded cloud; 
A diamond evening-star; 
Sad blue hills afar; 
Love in his shroud. 

Scarcely a tear to shed; 
Hardly a word to say; 
The end of a summer day; 
Sweet Love dead."""


  • Once the program terminates, open the file with TextEdit if working on a Mac, or with Notepad if working on Windows (you can double-click it in Windows Explorer). Verify that the file exists and that it contains the poem. If you are ambitious, you may want to use the Console or the Terminal to locate the file the way we did in class, and display its contents on the screen using type (Windows) or cat (Mac).


  • Put the code that writes the poem to file in a function called writeTextFile( fileName, text ), where fileName is a parameter that will receive the name of the file, and text the name of a variable that will get the string to write to file. The function should 1) open the file for writing, 2) write text to the file, and 3) close the file.
Verify that your function works by deleting poem.txt and then running your new program. If you function is written correctly, it will have recreated the poem.txt file with the same contents as before.







Challenge 2

QuestionMark2.jpg
  • Get some inspiration from the "Read Examples" section above, and add some code to your program that will read the file just created and print its contents (all the lines) on the screen. (Basically, add a file.open() statement, a loop to read and print the lines, and a file.close(), and you're done.)
  • When this works, replace your code by a call to a function called readTextFile() that will open the file, get its contents as a long string (once again, go back to the "Read Examples" section above to see how to do that). The function at the end will use a return statement to return a long string that is equal to the full contents of the file.

Here is an example of how your program will use your new function to read the file and display the string:


        text = readTextFile(  "poem.txt" )
        for line in text.split( "\n" ):
            print( line )


Writing Numbers to File and Reading them Back


The concept of writing a list of numbers to a text file is simple, and illustrated in the diagram below:

[ 1, 2, 3, 5, 10 ]
    |
    |
    V
[ '1', '2', '3', '5', '10' ]
    |
    |
    V
 '1\n2\n3\n5\n10\n'       ==(write)==>   text-file

The concept of reading a list of numbers from a text file is simple as well, and illustrated in the diagram below:

 '1\n2\n3\n5\n10\n'    <==(read)==    text-file 
         |
         |
         V
[ '1', '2', '3', '5', '10' ]
         |
         |
         V
[ 1, 2, 3, 5, 10 ]




Same idea: you write a function that takes a list of numbers and writes them to file, one per line. Then you write a function that reads the numbers back, prints them, and computes their sum. This last part is very important, because to text files contain text, or strings, and when you read that back into variables that are supposed to contain numbers, you must transform the strings into numbers.

Here is the list of numbers to use, and an example of how to organize your main program:


numbers = [ 1, 2, 10, 100, 50, 7 ]

# write the list to file, one number per line
writeIntFile( "numbers.txt", numbers )

# read the file of ints, and return it as a list of ints.
newNumbers = readIntFile( "numbers.txt" )

# print the list of ints and their sum (should be 170)
for x in newNumbers:
    print( x )

print( "Sum = ", sum( newNumbers ) )


Hints
1) Text files contain only strings of characters. To store numbers in a file you have to write the number as a string. A good way to transform an integer into a one-line string is with "%d\n" % x , where x is the integer in question.
2) When reading the file of integers, just read the file and display the lines in it as text. Then little by little transform each line into an int. Then when that works, figure out how to add the ints to a list, one at a time.



Creating a Log


Add the function below to your program. Then call it from your main program and "play" with it for a little while. Figure out how to make it stop (read the code!)

from random import choice
def discussion():
     canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
     print( "Hello!" )
     while True:
           answer = input( "> " ).strip()
           if answer.lower() in [ "bye", "ciao", "later" ]:
                 break
           print( choice( canned ) )
     print( "Good bye!" )



Challenge 3

QuestionMark3.jpg
  • Add some new statements to your function so that it will record the conversation that is taking place on the screen in a log file. A log is simply a text file that contains a list of lines representing actions that have taken place at some point under some circumstances. You may want to call the log log.txt
  • Verify that when your function has terminated, a new file exists in your working directory, and that it contains a log of your conversation.
  • Run your function again. Finish it with "bye" and check the log file again. Notice that the old conversation has been erased by the new one.
If we had wanted to add the new conversation at the end of the old one (logs have a tendency to keep everything and never erase prior information), then should have opened the file differently. When we open a file like this:
   file = open ( "someFileName.ext", "w" )

the "w" indicates create the file if it does not exist, or erase it if it already exists, and start writing to it." To write to a file without erasing it, we simply replace the "w" by an "a" which means "append" to the end of the file, or create it if it doesn't exist.

   file = open( "someFileName.ext", "a" )


Challenge 4

QuestionMark4.jpg


  • Modify your program so that it appends to the log and never erases it.









Challenge 5

QuestionMark5.jpg


  • Create a new function called log( line ) that adds a new line to the log file. This function will assume the log file name is log.txt, open the log, append the line to it, and close it. Using it will make our original discussion function much simpler:


from random import choice
def discussion():
     canned = [ "Please go on...", "Is that so?", "Please tell me more.", "Really?" ]
     print( "Hello!" )
     log( "Hello!" )
     while True:
           answer = input( "> " ).strip()
           log( answer )
           if answer.lower() in [ "bye", "ciao", "later" ]:
                 break
           response = choice( canned )
           print( response )
           log( response )
     print( "Good bye!" )
     log( "Good bye!" )



Challenge 6

QuestionMark6.jpg


  • Instead of having canned answers defined in the program, let's put them in a text file. This may seem strange to put strings in a file, except if you think of the Eliza program for the previous homework where the program may add more canned answers to its list as the conversation with the human progresses. If the program were to save the list of canned answers to a file, and restore them from file when it restarts, the program would have "memory" and fool the user in thinking that the program "remembers" parts of a previous conversation.
  • Your challenge is to make your conversation function read the canned answers from a different text file where you will have saved canned sentences, one per line.






Submission


Submit the program (which you should name lab9.py) to this URL: http://cs.smith.edu/~thiebaut/111b/submitL9.php




...