[Python实战06]保存数据到文件中


之前我们从文件中进行读取数据,并把读取到的数据进行了简单的处理,然后通过print语句进行了打印。但是很多时候我们是需要把处理后的数据保存到文件中的,所以这里我们接着介绍如何把处理后的数据保存到文件,因为在之前只是对数据进行了非常简单的处理,这里首先对数据做一些复杂的处理。

程序处理数据

编写一段代码实现以下功能:创建两个名为man和other的空列表,读取sketch.txt文件中的内容(此文件在【Python实战04】中有),并使用“:”进行分割,分别保存为role和line_spoken,然后通过role为man或者other,将对应说的内容分别保存到对应的man和other列表中。
代码如下:
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!')
print(man)
print(other)
运行结果如下:
>>> ================================ RESTART ================================
>>> 
['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!']
["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!"]
>>> 
接着我们要做的工作就是把列表man和other中的内容保存到文件,首先就是要以写的方式打开一个文件。

以写模式打开一个文件

代码如下:
out = open('sketch.txt','w')
这里我们以写的模式打开了sketch.txt,然后我们可以通过以下语句将内容写到这个文件,如下:
print('Hello World',file=out)
这样我们就把Hello World这个字符串写入到了sketch.txt文件中去了,最后别忘了关闭流:
out.close()
然后我们就可以改写之前的代码,将man和other列表的内容分别保存至man_data.txt和other_data.txt中,代码如下:
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!')
print(man)
print(other)


try:
    man_file = open('man_data.txt','w')
    other_file = open('other_data.txt','w')


    print(man,file=man_file)
    print(other,file=other_file)


    man_file.close()
    other_file.close()
except IOError:
    print('File Error')
可以看到我们只是在之前的代码最后加入了文件的写操作,其他的代码并没有改动。执行以上的代码,可以发现在对应的文件夹中生成了一下的两个文件: \

两个文件的内容分别如下: 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!"]
但是此时我们的代码相对脆弱,因为在最后进行文件关闭时,如果第一个man_file.close()执行错误的话,则第二个other_file.close()则不会被执行,此时就导致了other_file的关闭失败,此时我们可以通过finally语句进行限制。

用finally拓展try

这里我们可以把数据关闭操作直接放置到finally语句中进行操作,如下:
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!')
print(man)
print(other)

try:
    man_file = open('man_data.txt','w')
    other_file = open('other_data.txt','w')

    print(man,file=man_file)
    print(other,file=other_file)

except IOError:
    print('File Error')
finally:
    man_file.close()
    other_file.close()
运行结果是和之前一样的,同样会生成对应的两个文件,不同的是处理错误的能力增强了。
补充:这里我们也可以对错误类型的详细信息进行打印,比如打开文件进行读取时,我们可以打印当前错误的详细信息,代码如下:
try:
    data = open('sketch1.txt')
except IOError as err:
    print('File Error:'+str(err))
这里为IOError异常起了一个别名err,并打印err中的内容,因为err为一个对象,所以使用str函数来打印对象的具体内容。结果如下:
>>> ================================ RESTART ================================
>>> 
File Error:[Errno 2] No such file or directory: 'sketch1.txt'
>>> 
这里就直接提示说当前没有找到sketch1.txt文件。


评论关闭