[Python实战07]用with来处理文件


由于处理文件时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语句会自动的帮我们进行处理的。

 

 

用with处理文件操作

既然有了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操作,这样代码也减少了许多,并且我们的代码的健壮性和增加了不少,下面是输出的结果: man_data.txt:
['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))
好了,现在我们可以运行这段代码了,但是在运行代码之前我们还有几件事情要强调下: 1、因为我们修改了之前的print_lol函数,而这个函数我放入到wukong这个模块中了,所以在当前这个读取文件中使用这个模块的话我们首先要把其加入到本地模块,具体如何加入可以参考【Python实战02】. 2、在当前的文件中导入之前的模块,如以上代码中第一行为:import wukong,即为导入了当前模块。 3、在with中的print语句中我们使用的是print_lol而不是之前的print函数了,这点切记。
注意以上三点以后,我们就可以执行以上的代码了,运行结果如下: man_data.txt:
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!
好了,全部搞定!







 

评论关闭