《Python核心编程》第二版第55页第三章练习 续二 Python核心编程答案自己做的

3-10.
异常。使用类似readTextFile.py中异常处理的方法取代makeTextFile.py中对os.path.exists()的调用。反过来,用os.path.exists()取代readTextFile.py中的异常处理方法。
【答案】
代码如下:
def makeTextFile():

    import os
    ls = os.linesep
   
    # get filename
    while True:
        fname = raw_input('Enter file name: ')
        try:
            open(fname, 'r')
            print" *** ERROR: '%s' already exists" % fname
        except IOError:
            break
            fname.close()

   
    # get file content (text) lines
    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-ending
    fobj = open(fname, 'w')
    fobj.writelines(['%s%s' % (x,ls) for x in all])
    fobj.close()
    print 'Done'

def readTextFile():

    # get filename
    fname = raw_input('Enter filename: ')
   
    import os
   
    if os.path.exists(fname):
        fobj = open(fname, 'r')
        for eachLine in fobj:
            print eachLine,
        fobj.close()  
    else:
        print 'Can not find this file!'

print "'m' means make a new text file."
print "'r' means read a text file."
choice = raw_input('Please input your choice ... ')
if choice == 'm': makeTextFile()
elif choice == 'r': readTextFile()
else: print'end'

3-11.
字符串格式化。不再抑制readTextFile.py中print语句生成的NEWLINE字符,修改你的代码,在显示一行之前删除每行末尾的空白。这样,你就可以移除print语句末尾的逗号了。提示:使用字符串对象的strip()方法。
【答案】
代码如下:
# get filename
fname = raw_input('Enter file name: ')

# 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.rstrip()
    fobj.close()

3-12.
合并源文件。将两段程序合并成一个,给它起一个你喜欢的名字,比如readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。
【答案】
代码如下:
def makeTextFile():

    import os
    ls = os.linesep
   
    # get filename
    while True:
        fname = raw_input('Enter file name: ')
        if os.path.exists(fname):
            print" *** ERROR: '%s' already exists" % fname
        else:
            break
   
    # get file content (text) lines
    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-ending
    fobj = open(fname, 'w')
    fobj.writelines(['%s%s' % (x,ls) for x in all])
    fobj.close()
    print 'Done'

def readTextFile():

    # 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()

print "'m' means make a new text file."
print "'r' means read a text file."
choice = raw_input('Please input your choice ... ')
if choice == 'm': makeTextFile()
elif choice == 'r': readTextFile()
else: print'end'

3-13.
*添加新功能。将你上一个问题改造好的readNwriteTextFiles.py增加一个新功能:允许用户编辑一个已经存在的文本文件。你可以使用任何方式,无论是一次编辑一行,还是一次编辑所有的文本。需要提醒一下的是,一次编辑全部文本有一定难度,你可能需要借助GUI工具包或一个基于屏幕文本编辑的模块比如curses模块。要允许用户保存他的修改(保存到文件)或取消他的修改(不改变原始文件),并且要确保原始文件的安全性(不论程序是否正常关闭)。
【答案】目前感觉有点难度,这个思考题只能押后了。


 

原文地址:https://www.cnblogs.com/balian/p/1940884.html