《Python核心编程》第二版第三章答案

时间:2023-03-09 20:22:58
《Python核心编程》第二版第三章答案

本人python新手,答案自己做的,如果有问题,欢迎大家评论和讨论!

更新会在本随笔中直接更新。

我在Windows使用python版本是2.7.0

  

3–10. 异常。使用类似readTextFile.py 中异常处理的方法取代 readTextFile.py makeTextFile.py 中对os.path.exists() 的调用。反过来, 用os.path.exists() 取代readTextFile.py 中的异常处理方法。

我的答案;

makeTextFile.py

 '''
@auther:Feng Xu
'''
'makeTextFile.py -- create text file' import os
ls = os.linesep #get file name
while True:
fname = raw_input('Input your filename:')
#利用读文件来检查fname文件是否存在,如果存在打印错误信息,关闭文件,继续循环;不存在直接异常break退出while循环
try:
fobj = open(fname, 'r')
print "***Error: %s already exists" % fname
except IOError, e:
break
else:
fobj.close() all = []
print "\nEnter lines('.' by itself to quit).\n" # loop until user terminates input
while True:
entry = raw_input('-->')
if entry == '.':
break
else:
all.append(entry) # write lines to file with proper line-coding
fobj = open(fname, 'w')
for x in all:
fobj.writelines('%s%s' % (x, ls))
fobj.close() print 'Done!'

readTextFile.py

 '''
@auther:Feng Xu
'''
'readTextFile.py -- read and display text file' import os while True:
fname = raw_input('Enter filename:')
if os.path.exists(fname):
break
else:
print "Error: %s not exists" % fname #display contents to the screen
fobj = open(fname, 'r')
for eachline in fobj:
print eachline,
fobj.close()

【未完】