由于处理文件时try/except/finally经常会使用到,所以Python提供了一个语句来替换该种模式,就是使用with语句,使用with进行文件操作时就不需要进行finally操作了,如下:
try: with open(‘data.txt‘,‘w‘) as data: print(‘Hello World‘,file=data) except IOError as err: print(‘File Error:‘+str(err))如上,在进行文件的写入时,我们使用with进行操作,从而在最后不需要加入finally语句进行数据的关闭操作了,with语句会自动的帮我们进行处理的。
man= [] other = [] try: data = open(‘sketch.txt‘) for each_line in data: try: (role,line_spoken) = each_line.split(":",1) line_spoken = line_spoken.strip() if role == ‘Man‘: man.append(line_spoken) elif role == ‘Other Man‘: other.append(line_spoken) except ValueError: pass data.close() except IOError: print(‘The datafile is missing!‘) try: with open(‘man_data.txt‘,‘w‘) as man_file: print(man,file=man_file) with open(‘other_data.txt‘,‘w‘) as other_file: print(other,file=other_file) except IOError as err: print(‘File Error:‘+str(err))好了,我们已经将文件的写入操作换成了with操作,这样代码也减少了许多,并且我们的代码的健壮性和增加了不少,下面是输出的结果:
[‘Is this the right room for an argument?‘, "No you haven‘t!", ‘When?‘, "No you didn‘t!", "You didn‘t!", ‘You did not!‘, ‘Ah! (taking out his wallet and paying) Just the five minutes.‘, ‘You most certainly did not!‘, "Oh no you didn‘t!", "Oh no you didn‘t!", "Oh look, this isn‘t an argument!", "No it isn‘t!", "It‘s just contradiction!", ‘It IS!‘, ‘You just contradicted me!‘, ‘You DID!‘, ‘You did just then!‘, ‘(exasperated) Oh, this is futile!!‘, ‘Yes it is!‘]other_data.txt:
["I‘ve told you once.", ‘Yes I have.‘, ‘Just now.‘, ‘Yes I did!‘, "I‘m telling you, I did!", "Oh I‘m sorry, is this a five minute argument, or the full half hour?", ‘Just the five minutes. Thank you.‘, ‘Anyway, I did.‘, "Now let‘s get one thing quite clear: I most definitely told you!", ‘Oh yes I did!‘, ‘Oh yes I did!‘, ‘Yes it is!‘, "No it isn‘t!", ‘It is NOT!‘, "No I didn‘t!", ‘No no no!‘, ‘Nonsense!‘, "No it isn‘t!"]细心的读者可能会发现,在进行处理之前,一句话就是一行,而处理之后所有的话都在一样了,所以我们还需要继续进行处理,让每一句话占用一行,可是怎样处理呢?还记得我们之前编写的print_lol函数吗?对,就是以下的这段代码:
"""这里是wukong模块,print_lol函数专门用来输出一个列表""" """增加一个level参数,表示在遇到嵌套输出时控制制表符的输出""" def print_lol(movies,indent=False,level=0): for item_1 in movies: if isinstance(item_1,list): print_lol(item_1,indent,level+1) else: if indent: for tab_stop in range(level): print("\t",end=‘‘) print(item_1)这里我们是进行了数据格式控制的,我们何不使用这个函数呢?可以这个函数中没有对应的file参数,那么我们首先要做的就是修改这个函数喽,好吧,继续加入参数吧,代码如下:
"""这里是wukong模块,print_lol函数专门用来输出一个列表""" """增加一个level参数,表示在遇到嵌套输出时控制制表符的输出""" import sys def print_lol(movies,indent=False,level=0,out=sys.stdout): for item_1 in movies: if isinstance(item_1,list): print_lol(item_1,indent,level+1,out) else: if indent: for tab_stop in range(level): print("\t",end=‘‘,file=out) print(item_1,file=out)这里我们加入了参数out=sys.stdout,我们知道=号后面的为默认值,此时的默认值为sys.stdout,即表示如果没有值的话直接向屏幕进行输出。这里注意我们在第一行导入了sys
import wukong man= [] other = [] try: data = open(‘sketch.txt‘) for each_line in data: try: (role,line_spoken) = each_line.split(":",1) line_spoken = line_spoken.strip() if role == ‘Man‘: man.append(line_spoken) elif role == ‘Other Man‘: other.append(line_spoken) except ValueError: pass data.close() except IOError: print(‘The datafile is missing!‘) try: with open(‘man_data.txt‘,‘w‘) as man_file: wukong.print_lol(man,out=man_file) with open(‘other_data.txt‘,‘w‘) as other_file: wukong.print_lol(other,out=other_file) except IOError as err: print(‘File Error:‘+str(err))好了,现在我们可以运行这段代码了,但是在运行代码之前我们还有几件事情要强调下:
Is this the right room for an argument? No you haven‘t! When? No you didn‘t! You didn‘t! You did not! Ah! (taking out his wallet and paying) Just the five minutes. You most certainly did not! Oh no you didn‘t! Oh no you didn‘t! Oh look, this isn‘t an argument! No it isn‘t! It‘s just contradiction! It IS! You just contradicted me! You DID! You did just then! (exasperated) Oh, this is futile!! Yes it is!other_data.txt:
I‘ve told you once. Yes I have. Just now. Yes I did! I‘m telling you, I did! Oh I‘m sorry, is this a five minute argument, or the full half hour? Just the five minutes. Thank you. Anyway, I did. Now let‘s get one thing quite clear: I most definitely told you! Oh yes I did! Oh yes I did! Yes it is! No it isn‘t! It is NOT! No I didn‘t! No no no! Nonsense! No it isn‘t!好了,全部搞定!
原文:http://blog.csdn.net/wukongcode/article/details/18194799