1 defines a function func (filepath) FilePath: Opens the file with the with implementation for the file name, and outputs the file contents.
1 # -*-coding:utf-8-*- 2 3 4 def func (filepath): 5 6 return Aj.read () 7 8 Print func (r'e:/system.txt')
2 defines a function func (listinfo) Listinfo: For the list,Listinfo = [133, V, +, 232,----],
The returned list is less than 100, and is an even number
1 #-*-coding:utf-8-*-2 3 4 defFunc2 (listinfo):5 Try:6result = Filter (LambdaK:k < 100 andK% 2 = =0, Listinfo)7 exceptException as E:8 returne9 Else:Ten returnresult One AListinfo = [133, 88, 24, 33, 232, 44, 11, 44] - PrintFunc2 (Listinfo)
3 Define an exception class, inherit the exception class, and capture the following procedure: Determine whether the string length of the raw_input () input is less than 5, if it is less than 5, such as an input length of 3, output Yes, greater than 5 output no
1 #-*-coding:utf-8-*-2 3 4 classMy_error (Exception):5 6 def __init__(SELF,STR1):7Self.leng =Len (str1)8 9 defprocess (self):Ten ifSelf.leng < 5: One return 'Yes' A Else: - return 'No' - Try: the RaiseMy_error ('Sktaa') - exceptMy_error as E: - PrintE.process ()4. Write the With Operation Class FileInfo () to define the __enter__ and __exit__ methods. Complete the function:
4.1 opens FileInfo (filename) in the __enter__ method and returns the contents of the filename. If the file does not exist, you need to catch the exception.
4.2 Record the current date and file name of the file open in the __enter__ method. And keep the recorded information as Log.txt. Content format: "2014-4-5 xxx.txt"
1 #-*-coding:utf-8-*-2 ImportLogging3 Import Time4NewTime =time.time ()5 6 7 classFileinfo (object):8 def __init__(self, filename):9Self.filename =filenameTen One def __enter__(self): A Try: -F1 = open (Self.filename,'R') -Content =F1.read () the exceptIndexerror as E: - PrintSTR (e) +"The file doesn ' t exist" - Else: - f1.close () + returncontent - + def __exit__(self, exc_type, Exc_val, EXC_TB): AWith open ('Log.txt','A +') as log_f1: atLog_f1.write ('%s%s\n'% (Fileinfo.newtime,self.filename))5 defines a function func (urllist), urllist as a list of URLs, such as: [' http://xxx.com ', ' http:///xxx.com ', ' http://xxxx.cm ' ...]. The functions are as follows:
5.1 Open the URL in turn
5.2 Print the URL corresponding to the content
5.3 If the URL is not open, then the URL is logged to the log file, skip the continued access to the next URL
1 #-*-coding:utf-8-*-2 ImportUrllib3 ImportLogging4 5 6Logger =Logging.getlogger ()7HDLR = logging. Filehandler ('Sendlog.log')8Formatter = logging. Formatter ('% (message) s')9 Hdlr.setformatter (Formatter)Ten Logger.addhandler (HDLR) One Logger.setlevel (logging. NOTSET) A - - deffunc (urllist): the forIinchurllist: - Try: -U =Urllib.urlopen (i) - exceptIOError: + Logging.error (i) - Else: + PrintU.read A finally: at u.close () -Func (['http://www.baidu.com','http://weibo.com'])
Exercises for exception handling in Python