Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Now we know how to get the lines from the file let's consider the body of the numwords() function. First we want to create a list of words in a line. By looking at the Python reference documentation for the string module we see there is a function called split which separates a string into a list of fields separated by whitespace (or any other character we define). Finally, by again referring to the documentation we see that the builtin function len() returns the number of elements in a list, which in our case should be the number of words in the string - exactly what we want.

So the final code looks like:

import string def numwords(s):

list = string.split(s) # need to qualify split() with string module

return len(list) # return number of elements in list

inp = open("menu.txt","r")

total = 0 # initialise to zero; also creates variable

for line in inp.readlines():

total = total + numwords(line) # accumulate totals for each line print "File had %d words" % total

inp.close()

That's not quite right of course because it counts the '&' character as a word (although maybe you think it should...). Also, it can only be used on a single file (menu.txt). But its not too hard to convert it to read the filename from the command line ( argv[1]) or via raw_input() as we saw in the 'Talking to the user' section. I leave that as an excercise for the reader.

BASIC and Tcl

BASIC and Tcl provide their own file handling mechanisms. They aren't too different to Python so I'll simply show you the 'cat' program in both and leave it at that.

BASIC Version

BASIC uses a concept called streams to identify files. These streams are numbered which can make BASIC file handling tedious. This can be avoided by using a handy function called ??? which retirns the next free stream number. If you store this in a variable you never need to get confused about which stream/file has which number.

INFILE = FREEFILE

OPEN "TEST.DAT" FOR INPUT AS INFILE

REM Check for EndOfFile(EOF) then

REM read line from input and print it

DO WHILE NOT EOF(INFILE)

LINE INPUT #INFILE, theLine

PRINT theLine

CLOSE #INFILE

Tcl Version

By now the pattern should be clear. Here is the Tcl version:

set infile [open "Test.dat" r] while { [gets $infile line] >= 0} {

puts $line

}

64

close $infile

Things to remember

Open files before using them

Files can usually only be read or written but not both at the same time

Pythons readlines() function reads all the lines in a file, while readline() only reads one line at a time, which may help save memory.

Close files after use.

65