that exists now or in the future to all of the lines in a text file. If we code this module
and put it in a directory on the module search path, we can use it any time we need to
step through a file line by line. Example 4-2 is a client script that does simple line
translations.
Example 4-2. PP4E\System\Filetools\commands.py
#!/usr/local/bin/python
from sys import argv
from scanfile import scanner
class UnknownCommand(Exception): pass
def processLine(line): # define a function
if line[0] == '*': # applied to each line
print("Ms.", line[1:-1])
elif line[0] == '+':
print("Mr.", line[1:-1]) # strip first and last char: \n
else:
raise UnknownCommand(line) # raise an exception
filename = 'data.txt'
if len(argv) == 2: filename = argv[1] # allow filename cmd arg
scanner(filename, processLine) # start the scanner
The text file hillbillies.txt contains the following lines:
*Granny
+Jethro
*Elly May
+"Uncle Jed"
and our commands script could be run as follows:
C:\...\PP4E\System\Filetools> python commands.py hillbillies.txt
Ms. Granny
Mr. Jethro
Ms. Elly May
Mr. "Uncle Jed"
This works, but there are a variety of coding alternatives for both files, some of which
may be better than those listed above. For instance, we could also code the command
processor of Example 4-2 in the following way; especially if the number of command
options starts to become large, such a data-driven approach may be more concise
and easier to maintain than a large if statement with essentially redundant actions (if
you ever have to change the way output lines print, you’ll have to change it in only one
place with this form):
commands = {'*': 'Ms.', '+': 'Mr.'} # data is easier to expand than code?
def processLine(line):
try:
print(commands[line[0]], line[1:-1])
except KeyError:
raise UnknownCommand(line)
File Tools | 161