3–10. 异常。使用类似readTextFile.py 中异常处理的方法取代 readTextFile.py,makeTextFile.py 中对os.path.exists() 的调用。反过来, 用s.path.exists() 取代readTextFile.py 中的异常处理方法。
【答】修改后的makeTextFile.py
import os
ls=os.linesep
while 1:
fname=raw_input('Enter filename: ')
try:
fobj=open(fname,'w')
except IOError, e:
print "Error:file open error", e
else:
break
all=[]
print "\nEnter lines('.' by itself to quit).\n"
while 1:
entry=raw_input('> ')
if entry=='.':
break
else:
all.append(entry)
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'Done!'
#readTextFile.py代码:
import os
fname=raw_input('Enter filenam: ')
print
if os.path.exists(fname):
fobj=open(fname,'r')
for eachline in fobj:
print eachline,
fobj.close()
else:
print "ERROR: '%s' file open error" %fname3–11.字符串格式化 不再抑制readTextFile.py 中 print 语句生成的 NEWLINE 字符,修改你的代码, 在显示一行之前删除每行末尾的空白。这样, 你就可以移除 print 语句末尾的逗号了。提示: 使用字符串对象的 strip()方法
【答】仅需要修改一句
print eachline.strip()3–12. 合并源文件。将两段程序合并成一个,给它起一个你喜欢的名字,比方readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。
【答】
import os
ls=os.linesep
while 1:
print "(1)male a text file"
print "(2)read a text file"
print "(x)exit"
option=raw_input('please choose a option: ')
if option=='1':
while 1:
fname=raw_input('Enter filename: ')
try:
fobj=open(fname,'w')
except IOError, e:
print "Error:file open error", e
else:
break
all=[]
print "\nEnter lines('.' by itself to quit).\n"
while 1:
entry=raw_input('> ')
if entry=='.':
break
else:
all.append(entry)
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'Done!'
elif option=='2':
fname=raw_input('Enter filenam: ')
print
if os.path.exists(fname):
fobj=open(fname,'r')
for eachline in fobj:
print eachline,
fobj.close()
print
else:
print "ERROR: '%s' file open error" %fname
elif option=='x' or option=='X':
break
else:
print "wrong option,please input again"3–13. 添加新功能。将你上一个问题改造好的 readNwriteTextFiles.py 增加一个新功能:允许用户编辑一个已经存在的文本文件。 你可以使用任何方式,无论是一次编辑一行,还是一次编辑所有文本。需要提醒一下的是, 一次编辑全部文本有一定难度,你可能需要借助 GUI工具包或一个基于屏幕文本编辑的模块比如 curses 模块。要允许用户保存他的修改(保存到文件)或取消他的修改(不改变原始文件),并且要确保原始文件的安全性(不论程序是否正常关闭)。
【答】暂时没做.
本文通过修改readTextFile.py和makeTextFile.py,展示了如何利用Python的异常处理机制替代os.path.exists()检查,以及如何用os.path.exists()替换异常处理来确保文件操作的可靠性。
1028

被折叠的 条评论
为什么被折叠?



