---
title: "Python第四课-深入文件与异常（数据持久化）"
author: "yuanta11"
date: "2012-09-14T00:43:22Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2012-09-14T02:32:10Z"
id: 1678231
url: "https://pythonmap.iteye.com/blog/1678231"
---

[Python第三课——初探文件与异常](http://pythonmap.iteye.com/blog/1674531) 学习的主要是从文件读取数据、异常处理基本语法
本节课学习如何使用Python向文本文件中写入数据、异常处理的深入补充


**1、创建文件，并将需要持久化得数据写入文件中。**

```python

'''将上课demo中的谈话内容（conversations）按角色（role）的不同，分别存入两个文本文件中'''

man = [] #分别定义两个list 用来存储两个role的conversations
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man': #通过判断role来确定要存入的list
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close() #别忘了完成文件操作关闭数据文件对象
except IOError:
    print('The file is missing!')

try:
    man_file = open('man_data.txt', 'w') #数据文件对象中的文件参数如果不存在，并且相应目录有相应权限，open()会自动创建文件
    other_file = open('other_data.txt', 'w') # 'w'为文件数据对象的'写'模式

    print(man, file = man_file) #print()函数中的file参数为写入的文件名
    print(other, file = other_file)

    man_file.close() #别忘了完成文件操作关闭数据文件对象
    other_file.close()
except IOError:
    print('File Error!')

```



**2、改进上面代码中的异常处理逻辑和代码：**

上面代码中的异常处理方式依旧是不完善的，想想看，如果在man_file.close()语句之前，代码发生了错误，那么数据文件对象是不会被关闭掉的。

改进代码：


```python

man = [] 
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man':
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close()
except IOError as ioerr: #将IOError异常对象赋予ioerr变量
    print('File Error :' + str(ioerr)) #将ioerr转换为字符串类型

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 as ioerr:
    print('File Error: ' + str(ioerr))
finally: #无论try代码块或者except代码块中的语句是否被执行，finally代码块中的语句
    if 'man_file' in locals(): #判断数据文件对象是否存在，loclas() BIF返回作用域中所有变量的字典
        man_file.close()
    if 'man_file' in locals():
        man_file.close()

```



**3、Python中 文件处理的语法糖：**

利用with语句，可以将文件处理的代码简化，无需考虑关闭文件，裁剪掉文件异常处理语句中的finally语句。
作用一：简化语法，减少工作量。
作用二：通过逻辑抽象，减少码农脑细胞死亡速度和出错概率。

对以上代码第二段之改进：

```python

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 ioerr:
    print('File Error: ' + str(ioerr))

```

OR

```python

try:
    with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
        print(man, file = man_file)
        print(other, file = other_file)
except IOError as ioerr:
    print('File Error: ' + str(ioerr))

```