Python-Day08-文件操作和异常处理

Author: Seven_0507
Date: 2019-05-23

Python-Day08-文件操作和异常处理_第1张图片

文章目录

  • 文件操作和异常处理
    • 1. 读写文本文件
    • 2. 读写二进制文件
    • 3. 读写JSON文件
    • 4. 读写CSV文件

文件操作和异常处理

1. 读写文本文件

"""
从文本文件中读取数据
 - 读取整个文件
 - for-in循环逐行读取
 - readlines方法将文件按行读取到一个列表容器中
"""
import time


def main():
    # 一次性读取整个文件内容
    with open('E:/Python/Python-100Days/data/致橡树.txt', 'r', encoding='utf-8') as f:
        print(f.read()) 
    print('-'*50)
#     f = open('E:/Python/Python-100Days/data/致橡树.txt', 'r', encoding='utf-8')
#     print(f.read())
#     f.close() 用来关闭文件对象释放资源
#     可通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源

    # 通过for-in循环逐行读取
    with open('E:/Python/Python-100Days/data/致橡树.txt', mode='r', encoding='utf-8') as f:
        for line in f:
            print(line, end='')
            time.sleep(0.5)
    print()
    print('-'*50)
    
    # 读取文件按行读取到列表中
    with open('E:/Python/Python-100Days/data/致橡树.txt', encoding='utf-8') as f:
        lines = f.readlines()
    print(lines)
    

if __name__ == '__main__':
    main()
我如果爱你
绝不学攀援的凌霄花
借你的高枝炫耀自己

我如果爱你
绝不学痴情的鸟儿
为绿荫重复单调的歌曲


--------------------------------------------------
我如果爱你
绝不学攀援的凌霄花
借你的高枝炫耀自己

我如果爱你
绝不学痴情的鸟儿
为绿荫重复单调的歌曲


--------------------------------------------------
['\ufeff我如果爱你\n', '绝不学攀援的凌霄花\n', '借你的高枝炫耀自己\n', '\n', '我如果爱你\n', '绝不学痴情的鸟儿\n', '为绿荫重复单调的歌曲\n', '\n']
"""
异常机制 - 处理程序在运行时可能发生的状态
 - 若open函数指定的文件并不存在或者无法打开,那么将引发异常状况导致程序崩溃
"""

def main():
    f = None
    try:
        with open('E:/Python/Python-100Days/data/致橡树11.txt', 'r', encoding='utf-8') as f:
            lines = f.readlines()
    except FileNotFoundError as msg:
        print('无法打开指定的文件!')
        print(msg)
    except LookupError:
        print('指定了未知的编码!')
    except UnicodeDecodeError:
        print('非文本文件无法解码!')
        sys.exit()
#     except合并语句
#     except (FileNotFoundError, LookupError, UnicodeDecodeError) as msg:
#         print(msg)
    else:
        for line in lines:
            print(line.rstrip())
            time.sleep(0.5)

    # finally 用来释放外部资源
    finally:
        # 此处最适合做善后工作
        print('不管发生什么我都会执行')


if __name__ == '__main__':
    main()
无法打开指定的文件!
[Errno 2] No such file or directory: 'E:/Python/Python-100Days/data/致橡树11.txt'
不管发生什么我都会执行
"""
将文本信息写入文件
eg:1-9999之间的素数分别写入三个文件中
"""
from math import sqrt


def is_prime(n):
    """判断素数的函数"""
    assert n > 0
    for factor in range(2, int(sqrt(n)) + 1):
        if n % factor == 0:
            return False
    return True if n != 1 else False


def main():
    filenames = ('E:/Python/Python-100Days/data/a.txt'
                 ,'E:/Python/Python-100Days/data/b.txt'
                 ,'E:/Python/Python-100Days/data/c.txt')
    fs_list = []
    try:
        for filename in filenames:
            # 打开文件
            fs_list.append(open(filename, 'w', encoding='utf-8'))
        for number in range(1, 10000):
            if is_prime(number):
                if number < 100:
                    # 写入文本内容
                    fs_list[0].write(str(number) + '\n')
                elif number < 1000:
                    fs_list[1].write(str(number) + '\n')
                else:
                    fs_list[2].write(str(number) + '\n')
    except IOError as ex:
        print(ex)
        print('写文件时发生错误!')
    finally:
        for fs in fs_list:
            fs.close()
    print('操作完成!')


if __name__ == '__main__':
    main()
操作完成!

2. 读写二进制文件

"""
读写二进制文件
eg:实现复制图片文件的功能
"""
def main():
    try:
        # 读入图片文件
        with open('E:/Python/Python-100Days/data/guido.jpg', 'rb') as fs1:
            data = fs1.read()
            print(type(data))  # 
        # 写入图片文件
        with open('E:/Python/Python-100Days/data/猴子.jpg', 'wb') as fs2:
            fs2.write(data)
    except FileNotFoundError as e:
        print('指定的文件无法打开.')
    except IOError as e:
        print('读写文件时出现错误.')
    print('程序执行结束.')


if __name__ == '__main__':
    main()

程序执行结束.

3. 读写JSON文件

"""
读写JSON文件
将一个列表或者一个字典中的数据保存到文件中
"""
import json


def main():
    # 字典数据
    mydict = {'name': '五月猴'
              ,'age': 27
              ,'qq': 123456
              ,'friends': ['七月静', '文静']
              ,'cars': [{'brand': 'BYD', 'max_speed': 180}
                        ,{'brand': 'Audi', 'max_speed': 280}
                        ,{'brand': 'Benz', 'max_speed': 320}]
             }
    try:
        # 打开json文件
        with open('E:/Python/Python-100Days/data/data.json', 'w', encoding='utf-8') as fs:
            # 写入json文件中
            json.dump(mydict, fs)
    except IOError as e:
        print(e)
    print('保存数据完成!')


if __name__ == '__main__':
    main()
保存数据完成!

4. 读写CSV文件

"""
读取CSV文件
"""
import csv

filename = 'E:/Python/Python-100Days/data/example.csv'

try:
    with open(filename) as f:
        reader = csv.reader(f)
        data = list(reader)
except FileNotFoundError:
    print('无法打开文件:', filename)
else:
    for item in data:
        print('%-30s%-20s%-10s' % (item[0], item[1], item[2]))
print('-'*80)


"""
写入CSV文件
"""
import csv

class Teacher(object):

    def __init__(self, name, age, title):
        self.__name = name
        self.__age = age
        self.__title = title
        self.__index = -1

    @property
    def name(self):
        return self.__name
    
    @property
    def age(self):
        return self.__age
    
    @property
    def title(self):
        return self.__title

filename = 'E:/Python/Python-100Days/data/teacher.csv'
teachers = [Teacher('五月猴', 27, '学僧'), Teacher('狄仁杰', 25, '砖家')]

try:
    with open(filename, 'w') as f:
        writer = csv.writer(f)
        for teacher in teachers:
            writer.writerow([teacher.name, teacher.age, teacher.title])
except BaseException as e:
    print('无法写入文件:', filename)
else:
    print('保存数据完成!')
4/5/2014 13:34                Apples              73        
4/5/2014 3:41                 Cherries            85        
4/6/2014 12:46                Pears               14        
4/8/2014 8:59                 Oranges             52        
4/10/2014 2:07                Apples              152       
4/10/2014 18:10               Bananas             23        
4/10/2014 2:40                Strawberries        98        
--------------------------------------------------------------------------------
保存数据完成!

你可能感兴趣的:(Python)