异常和文件操作

异常和文件操作

异常

1.异常 - 程序报错

当程序出现了异常,程序直接结束

print('=====')
# print('abc'[5])
print('-----')
print('+++++')

2.异常捕获

异常捕获就是让程序在出现异常的时候不崩溃还可以接着往后执行

1)语法1: - 捕获所有类型的异常
try:
代码段1(需要捕获异常的代码)
except:
代码段2(捕获到异常后会执行的代码)
finally:
代码段
其他代码

2)执行过程:先执行代码段1,如果代码段1在执行过程中出现了异常,程序不会奔溃,直接执行代码段2,执行完代码段2才继续执行后续其他代码。

try:
    print('====')
    print('abc'[5])
    print('++++')
except:
    print('前面出现了异常')

3.异常捕获其他语法

语法二: - 捕获指定的一种异常

try:
    代码段1(需要捕获异常的代码)
except 异常类型:
    代码段2(捕获到异常后会执行的代码)
finally:
    代码段
其他代码

# print('abc'[5])     # IndexError
# age = int(input('请输入年龄:'))     # ValueError
# try:
#     age = int(input('请输入年龄:'))
#     print(age + 'acb')    # TypeError
# except ValueError:
#     print('输入有误,年龄必须是整数!')

语法三: - 同时捕获多种异常,针对不同的异常做相同的处理

try:
    代码段1(需要捕获异常的代码)
except (异常类型1, 异常类型2, 异常类型3,...):
    代码段2(捕获到异常后会执行的代码)
finally:
    代码段
其他代码

语法四:- 同时捕获多种异常,针对不同的异常做不一样的处理

try:
    代码段1(需要捕获异常的代码)
except 异常类型1:
    代码段11
except 异常类型2:
    代码段22
except 异常类型3:
    代码段33
...
finally:
    代码段
其他代码

4.finally

finally后面的代码段不管被捕获的代码发生了什么都会执行(就算try后面的代码出现异常没有被捕获导致程序奔溃,finally后面的代码也会执行)

# try:
#     print({'a': 10}['b'])
# except IndexError:
#     print('下标越界!')
# finally:
#     print('写遗书')
# print('其他语句')

5.抛出异常

raise 异常类型

class AgeError(Exception):
    def __str__(self):
        return '年龄值的有效范围是0~200'


age = int(input('请输入年龄:'))
if age > 200 or age < 0:
    raise AgeError

文件操作

1.数据持久化(数据本地化)
默认情况下程序中的数据都是保存在运行内存中,运行内存中是数据在程序结束的时候会自动销毁
如果希望程序结束后数据不销毁就必须将数据以文件的形式保存在硬盘中。
常用的文件格式:数据库文件(sqlit、db)、json文件(.json)、plist文件(.plist)、表格文件(xls、xlsx、csv)、二进制文件(图片、视频、音频)、普通文件(txt)

2.文件操作(文件内容的操作) - I/O操作
基本步骤:打开文件 -> 操作文件(读、写) -> 关闭文件
1)打开文件

open(file, mode=‘r’, *, encoding=None) - 以指定模式打开指定文件,并且返回文件对象
file - 需要打开的文件在计算机中的位置(文件路径)
绝对路径:文件在计算机中全路径(/Users/yuting/授课/Python2102/01语言基础/day13-异常捕获和文件操作/test.txt)
相对路径:在写路径的时候用一个点或者多个点来表示文件绝对路径的一部分
. - 表示当前目录(当前目录指的时候当前写代码的文件所在的目录),
… - 表示当前目录的上层目录
… - 表示当前目录的上层目录的上层目录
注意:如果只有一个点,这个点可以省略
mode - 决定打开文件后能进行的操作是读还是写?同时决定操作文件的时候对应数据的类型是字符串还是二进制 (mode需要两个值)
第一类值:控制读写
r - 只读(默认); 如果打开的文件不存在会报错FileNotFoundError
w - 只写;会清空原文件中的内容;如果打开的文件不存在,不报错并且自动创建对应的文件(如果路径中的文件夹不存在会报错)
a - 只写;会保留原文件中的内容;如果打开的文件不存在,不报错并且自动创建对应的文件(如果路径中的文件夹不存在会报错)
第二类值:控制操作数据的类型
t - 文本模式,对应的数据类型是str (文本文件才可以使用t来打开)(默认)
b - 二进制模式,对应的数据类型是bytes

案例:rt、tr、r; rb、br; wt、tw、w; wb、bw; at、ta、a; ab、ba

encoding - 设置文本文件的编码方式(只能在以t的模式打开文本文件的时候才需要设置)
一般设置成utf-8,原则是:对同一个文件进行读和写的时候打开时对应的编码方式要一致

第一个参数:file

# open(r'/Users/yuting/授课/Python2102/01语言基础/day13-异常捕获和文件操作/test.txt')
# open('./test.txt')

第二个参数:mode

r

# f = open('test.txt', 'r')
# f.read()
# f.write('abc')    # io.UnsupportedOperation: not writable

w

# f = open('test.txt', 'w')
# f.write('abc')
# f.read()        # io.UnsupportedOperation: not readable

a

# f = open('test.txt', 'a')
# f.write('abc')
# f.read()        # io.UnsupportedOperation: not readable

t

# f = open('test.txt', 'rt')
# result = f.read()
# print(type(result))     # <class 'str'>

b

# f = open('test.txt', 'rb')
# result = f.read()
# print(type(result))      # <class 'bytes'>

打开不存在的文件

# f = open('./test2.txt', 'r')   # FileNotFoundError: [Errno 2] No such file or directory: './test2.txt'
# f = open('./test2.txt', 'w')
# f = open('./test3.txt', 'a', encoding='utf-8')
  1. 操作文件

a. 读

文件对象.read() - 从读写位置开始读到文件结束

# f = open('test.txt', 'r')
# result = f.read()
# print(result)
# print('====================================')
# f.seek(0)           # 将读写位置移动到文件开头
# result = f.read()
# print(result)

文件对象.readlines() - 从读写位置开始读到文件结束,返回的是列表,列表中的元素是每一行内容(只能针对文本文件有效)

# f = open('test.txt', 'r')
# result = f.readlines()
# print(result)

文件对象.readline() - 从读写位置开始读到一行结束(只能针对文本文件有效)

# f = open('test.txt', 'rb')
# result = f.readline()
# print(result)    # aaaa
#
# result = f.readline()
# print(result)    # bbbb

下载图片

获取网络图片数据

import requests
response = requests.get('https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1404395923,1295062384&fm=26&gp=0.jpg')
print(response.content)

将图片数据保存到图片文件中

f = open('宝儿姐.jpg', 'bw')
f.write(response.content)

b. 写操作

文件对象.write(内容)

f = open('test.txt', 'wb')
# f.write(b'abc')

3)关闭文件 - 文件操作完成后需要关闭文件

文件对象.close()

# f = open('test.txt')
# print(f.read())
# f.seek(0)
# print(f.read())
# f.close()
# print(f.read())   # ValueError: I/O operation on closed file.

自动关闭关键

with open(file, mode=‘r’,*, encoding=None) as 文件对象:
操作文件

with open('test.txt') as f:
    print(f.read())

# print(f.read())     # ValueError: I/O operation on closed file.

1.数据持久化的方法

第一步:确定需要持久化的数据是什么
第二步:创建文件保持需要持久化的数据的初始值
第三步:在程序中需要这个数据的时候从文件中读出来
第四步:如果在程序中修改了这个数据,要将最新的数据更新到文件中

# 案例:打印程序的运行次数
def print_count():
    with open('count.txt', encoding='utf-8') as f:
        count = int(f.read())

    count += 1
    print(count)

    with open('count.txt', 'w', encoding='utf-8') as f:
        f.write(str(count))

print_count()


# 案例2:保存曾经添加的所有的名字
value = input('请输入数据:')

with open('name.txt', encoding='utf-8') as f:
    result = f.read()
names = eval(result)
names.append(value)
print(names)

with open('name.txt', 'w', encoding='utf-8') as f:
    f.write(str(names))

eval的用法

str1 = "[10, 20, 30]"    #  [10, 20, 30]
result = eval(str1)
print(result)           # [10, 20, 30]
print(type(result))     # <class 'list'>
print(result[-1])       # 30


str2 = "{'a': 10, 'b': 20}"    # {'a': 10, 'b': 20}
result = eval(str2)
print(result)           # {'a': 10, 'b': 20}
print(type(result))     # <class 'dict'>
print(result['a'])      # 10

作业

global choise

def input_account_password():
    account = input('请输入账号(3~6位):')
    password = input('请输入密码 (6~12位):')
    return (account,password)

def get_account_password():
    with open('account.txt','r') as f:
        lib_account = eval(f.read())
    with open('password.txt', 'r') as f:
        lib_password = eval(f.read())
    return (lib_account,lib_password)

def write_account_password(lib_account, lib_password):
    with open('account.txt', 'w') as f:
        f.write(str(lib_account))
    with open('password.txt','w') as f:
        f.write(str(lib_password))

def save_account_password(account,password):
    lib_account, lib_password = get_account_password()
    lib_account.append(account)
    lib_password.append(password)
    write_account_password(lib_account, lib_password)

def register():
    global choise
    account,password = input_account_password()
    lib_account,lib_password = get_account_password()
    if account in lib_account:
        print('注册失败!该账号已经注册过!')
    else:
        print('注册成功')
        save_account_password(account,password)


def login():
    global choise
    account, password = input_account_password()
    lib_account, lib_password = get_account_password()
    if  account not in lib_account:
        print('登录失败!该账号没有注册!')
    elif account in lib_account and lib_password[lib_account.index(account)] == password:
        print('登录成功!')
        choise = '3'
    else:
        print('登录失败!密码错误!')


def main_interface():
    global choise
    print('=='*11)
    print('** 欢迎来到XX管理系统 **')
    print('\t1.登\t录')
    print('\t2.注\t册')
    print('\t3.退\t出')
    print('=='*11)
    choise = input('请选择(1-3):')

while True:
    main_interface()
    if choise == '2':
        register()
    elif choise == '1':
        login()
    if choise == '3':
        print('已退出')
        break

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eDOzhuGr-1616070082683)(C:\Users\ly\AppData\Roaming\Typora\typora-user-images\image-20210318200407887.png)]

global choise
print('=='*11)
print('** 欢迎来到XX管理系统 **')
print('\t1.登\t录')
print('\t2.注\t册')
print('\t3.退\t出')
print('=='*11)
choise = input('请选择(1-3):')

while True:
main_interface()
if choise == ‘2’:
register()
elif choise == ‘1’:
login()
if choise == ‘3’:
print(‘已退出’)
break


[外链图片转存中...(img-eDOzhuGr-1616070082683)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yYPaiibI-1616070082684)(C:\Users\ly\AppData\Roaming\Typora\typora-user-images\image-20210318200423356.png)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值