Fork me on GitHub

《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 "\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"
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

 

posted @ 2014-04-12 23:47  whatbeg  阅读(1127)  评论(0编辑  收藏  举报