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 result 11 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 = filename 10 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 content 20 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.read 22 finally: 23 u.close() 24 func([‘http://www.baidu.com‘, ‘http://weibo.com‘])