Python中的異常處理的習題

來源:互聯網
上載者:User

標籤:exce   lambda   實現   www.   dha   color   index   else   並且   

1 定義一個函數func(filepath) filepath:為檔案名稱,用with實現開啟檔案,並且輸出檔案內容。

 

1 # -*- coding: UTF-8 -*-2 3 4 def func(filepath):5     with open(filepath) as aj: 6         return aj.read()7 8 print func(r‘E:/system.txt‘)

 

2 定義一個函數func(listinfo) listinfo:為列表,listinfo = [133, 88, 24, 33, 232, 44, 11, 44], 返回列表小於100,且為偶數的數

 

 1 # -*- coding: UTF-8 -*- 2  3  4 def func2(listinfo): 5     try: 6         result = filter(lambda k: k < 100 and k % 2 == 0, listinfo) 7     except Exception as e: 8         return e 9     else:10         return result11 12 listinfo = [133, 88, 24, 33, 232, 44, 11, 44]13 print func2(listinfo)

 

3定義一個異常類,繼承Exception類, 捕獲下面的過程:判斷raw_input()輸入的字串長度是否小於5,如果小於5,比如輸入長度為3則輸出yes,大於5輸出no
 1 # -*- coding: UTF-8 -*- 2  3  4 class my_error(Exception): 5  6     def __init__(self,str1): 7         self.leng = len(str1) 8  9     def process(self):10         if self.leng < 5:11             return ‘yes‘12         else:13             return ‘no‘14 try:15     raise my_error(‘sktaa‘)16 except my_error as e:17     print e.process()
4.編寫with操作類Fileinfo(),定義__enter__和__exit__方法。完成功能:

4.1 在__enter__方法裡開啟Fileinfo(filename),並且返回filename對應的內容。如果檔案不存在等情況,需要捕獲異常。

4.2 在__enter__方法裡記錄檔案開啟的當前日期和檔案名稱。並且把記錄的資訊保持為log.txt。內容格式:"2014-4-5 xxx.txt"

 1 # -*- coding: UTF-8 -*- 2 import logging 3 import time 4 newTime = time.time() 5  6  7 class Fileinfo(object): 8     def __init__(self, filename): 9         self.filename = filename10 11     def __enter__(self):12         try:13             f1 = open(self.filename,‘r‘)14             content = f1.read()15         except IndexError as e:16             print str(e) + "the file doesn‘t exist"17         else:18             f1.close()19             return content20 21     def __exit__(self, exc_type, exc_val, exc_tb):22         with open(‘log.txt‘,‘a+‘) as log_f1:23             log_f1.write(‘%s %s\n‘%(Fileinfo.newTime,self.filename))
5 定義一個函數func(urllist),urllist 為URL的列表,如:[‘http://xxx.com‘,‘http:///xxx.com‘,‘http://xxxx.cm‘....]。 功能如下:

5.1 依次開啟URL

5.2 列印URL對應的內容

5.3 若URL打不開,則把URL記錄到記錄檔,跳過繼續訪問下一個URL

 1 # -*- coding: UTF-8 -*- 2 import urllib 3 import logging 4  5  6 logger = logging.getLogger() 7 hdlr = logging.FileHandler(‘sendlog.log‘) 8 formatter = logging.Formatter(‘%(message)s‘) 9 hdlr.setFormatter(formatter)10 logger.addHandler(hdlr)11 logger.setLevel(logging.NOTSET)12 13 14 def func(urllist):15     for i in urllist:16         try:17             u = urllib.urlopen(i)18         except IOError:19             logging.error(i)20         else:21             print u.read22         finally:23             u.close()24 func([‘http://www.baidu.com‘, ‘http://weibo.com‘])

 

 

 

 

Python中的異常處理的習題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.