Python文件操作及异常处理
相对来说,Python的文件操作和异常处理比较简单,一些常用的方法将在下面的Demo中用到,直接上代码
文件处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import cPickle as p def fileOperation(): poem = 'Programming is fun When the work is done \ if you wanna make your work \ also fun:use Python!' f = file('c:\\poem.txt', 'a') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f = file('c:\\poem.txt') while True: line = f.read(1024) if len(line) == 0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Python f.close() def fileOperation2(): shoplistfile = 'shoplist.data' shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = file(shoplistfile, 'w') p.dump(shoplist, f) # dump the object to a file f.close() del shoplist # remove the shoplist # Read back from the storage f = file(shoplistfile) storedlist = p.load(f) print storedlist |
异常处理:
使用关键字try..except…finally,把所有可能引发异常的语句放在try块中,然后在except从句/块中处理所有的错误和异常,在finally块中指定最后操作。
except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。如果没有给出错误或异常的名称,它会处理 所有的 错误和异常。对于每个try从句,至少都有一个相关联的except从句。
如果某个错误或异常没有被处理,默认的Python处理器就会被调用。它会终止程序的运行,并且打印一个消息,我们已经看到了这样的处理,即系统默认打印异常信息。
还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
1 2 3 4 5 6 7 8 9 10 | import sys try: s = raw_input('Enter something --> ') except EOFError: print 'Why did you do an EOF on me?' sys.exit() # exit the program except: print 'Some error/exception occurred.' # here, we are not exiting the program print 'Done' |
使用关键字raise来抛出异常:
你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #A user-defined exception class. class ShortInputException(Exception): def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # Other work can continue as usual here except EOFError: print 'Why did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d, \ was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.' finally: print 'Done' |
没有评论