CIS200 Lab Week 7 : global variables and sequential text files --------------------------------------------------------- This material comes from Chapter 7 of the lecture notes and Dawson's text. Rather than lecture about it, we will cover it in lab. A computer program can read a text (.txt) file and write one. We'll do some experiments to see this. 1. Writing a text file: Do these experiments: make a command window. Then, do > cd Desktop > python >>> myfile = open("test.txt", "w") >>> myfile.write("this is line one\r\n") >>> myfile.write("line two\r\n") >>> myfile.close() (This ``opens'' a new file to be written and then writes two lines (strings) to it. The \r means ''return'' and \n means ``newline'' and are required to terminate a text line in a disk file. The last command ``closes'' the file so that others may view it.) Now, use notepad or some other editor to look at the file. 2. Reading a textfile: Do these experiments: >python >>> myfile = open("test.txt", "r") >>> text = myfile.readline() >>> text (This should print 'this is line one\r\n' Note the embedded newline character. The point is, readline grabs _all_ the characters in the file upto and including a newline character.) Next, do this: >>> text = text.strip() >>> text (this should print 'this is line one') Next, do this: >>> words = text.split(" ") >>> words (this should print, ['this', 'is', 'line', 'one'] ) Finally, do this: >>> text2 = myfile.readline() >>> text2 >>> text3 = myfile.readline() >>> text3 NOTICE THAT THE VALUE PRINTED FOR text3 IS THE EMPTY STRING, '' ! When a file is completely read, any subsequent reads will return the empty string. This is how you know you have read the entire file ! NOW, FINISH THE LAB EXERCISE: Download the Words.py module at www.cis.ksu.edu/~schmidt/200s08/Assign at the bottom of the page. Finish the module by writing the code for the initialize and nextWord functions. (Do initialize first, then nextWord. You can test the functions with the test program, TestWords.py that is listed immediately after Words.py on the web page.