• 《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

     1 '''
     2 @auther:Feng Xu
     3 '''
     4 'makeTextFile.py -- create text file'
     5 
     6 import os
     7 ls = os.linesep
     8 
     9 #get file name
    10 while True:
    11     fname = raw_input('Input your filename:')
    12     #利用读文件来检查fname文件是否存在,如果存在打印错误信息,关闭文件,继续循环;不存在直接异常break退出while循环
    13     try:
    14         fobj = open(fname, 'r')
    15         print "***Error: %s already exists" % fname
    16     except IOError, e:
    17         break
    18     else:
    19         fobj.close()
    20     
    21 all = []
    22 print "
    Enter lines('.' by itself to quit).
    "
    23 
    24 # loop until user terminates input
    25 while True:
    26     entry = raw_input('-->')
    27     if entry == '.':
    28         break
    29     else:
    30         all.append(entry)
    31 
    32 # write lines to file with proper line-coding
    33 fobj = open(fname, 'w')
    34 for x in all:
    35     fobj.writelines('%s%s' % (x, ls))
    36 fobj.close()
    37 
    38 print 'Done!'

    readTextFile.py

     1 '''
     2 @auther:Feng Xu
     3 '''
     4 'readTextFile.py -- read and display text file'
     5 
     6 import os
     7 
     8 while True:
     9     fname = raw_input('Enter filename:')
    10     if os.path.exists(fname):
    11         break
    12     else:
    13         print "Error: %s not exists" % fname
    14 
    15 #display contents to the screen
    16 fobj = open(fname, 'r')
    17 for eachline in fobj:
    18     print eachline,
    19 fobj.close()

    【未完】

  • 相关阅读:
    python 并发编程 多进程 互斥锁 目录
    python 并发编程 多进程 互斥锁
    python 并发编程 多进程 守护进程
    python 并发编程 多进程 Process对象的其他属性方法 terminate与is_alive name pid 函数
    python 并发编程 多进程 Process对象的其他属性方法 join 方法
    python 并发编程 多进程 目录
    POJ 2253
    POJ 2255
    POJ 2250
    POJ 2248
  • 原文地址:https://www.cnblogs.com/Skyar/p/3659074.html
Copyright © 2020-2023  润新知