56 CHAPTER4. COMPUTINGWITHSTRINGS
userfile.py
Program to createa file of usernames in batch mode.
import string
def main():
print "This programcreates a file of usernames from a"
print "file of names."
# get the filenames
infileName = raw_input("Whatfile are the names in? ")
outfileName = raw_input("Whatfile should the usernames go in? ")
# open the files
infile = open(infileName,’r’)
outfile = open(outfileName, ’w’)
# process eachline of the input file
for line in infile.readlines():
# get the firstand last names from line
first, last= string.split(line)
# create the username
uname = string.lower(first[0]+last[:7])
# write it to the outputfile
outfile.write(uname+’\n’)
# close both files
infile.close()
outfile.close()
print "Usernameshave been written to", outfileName
main()
Therearea fewthingsworthnoticinginthisprogram.I have two filesopenatthesametime,onefor
input(infile) andoneforoutput(outfile).It’s notunusualfora programtooperateonseveralfiles
simultaneously. Also,whencreatingtheusername,I usedthelowerfunctionfromthestring library.
Thisensuresthattheusernameis alllowercase,evenif theinputnamesaremixedcase.Finally, youshould
alsonoticethelinethatwritestheusernametothefile.
outfile.write(uname+’\n’)
Concatenatingthenewlinecharacteris necessaryto indicatetheendofline.Withoutthis,alloftheusernames
wouldruntogetherinonegiantline.
4.5.4 ComingAttraction:Objects
Have younoticedanythingstrangeaboutthesyntaxofthefileprocessingexamples?To applyanoperation
toa file,weusedotnotation. Forexample,toreadfrominfilewetypeinfile.read(). Thisis
differentfromthenormalfunctionapplicationthatwehave usedbefore.Afterall,totake theabsolutevalue
ofa variablex, wetypeabs(x), notx.abs().
InPython,a fileisanexampleofanobject. Objectscombinebothdataandoperationstogether. An
object’s operations,calledmethods, areinvokedusingthedotnotation. That’s whythesyntaxlooksa bit
different.