Chapter 3:

例3-1 makeTextFile.py

#!/usr/bin/env python

'makeTextFile.py'
import os
ls = os.linesep #get File name while True:
fname = raw_input("Enter file name: ")
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
else:
break #get file contents lines all = []
print "\nEnter lines('.' by itself to quit).\n" #loop until user terminate input while True:
entry = raw_input('> ')
if entry == '.':
break
else:
all.append(entry) #write lines to file with proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
#fobj.write('\n',join(all))
fobj.close()
print "DONE"

例3-2 readTextFile.py

#!/usr/bin/env python

'readTextFile.py'
#get filename
fname = raw_input('Enter filename: ')
print #attempt to open file for reading
try:
fobj = open(fname,'r')
except IOError, e:
print "*** file open error:", e
else:
#display contents to the screen
for eachLine in fobj:
print eachLine, fobj.close()
04-30 06:22