《Python核心编程》部分错误纠正(勘误表)(持续更新)

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 "
Enter lines('.' by itself to quit).
"

#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('
',join(all))
fobj.close()
print "DONE"
View Code

例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()
View Code
原文地址:https://www.cnblogs.com/whatbeg/p/3661616.html