Python基础5

1 捕获异常try...except...else...finally...

1.1 try...except...else...finally的使用

  • BUG分为两种:编辑器会爆红的bug + 逻辑性bug(小黄鸭式解决)
  • 多个异常类都是继承 BaseException (ctrl键查看-Pycharm)
  • try执行代码,except捕获错误
    • try里面的code执行出错,直接执行except内的语句
    • else里面的code在try中没错误时执行
    • finally有无异常都执行
  • 常见的错误异常及继承关系:https://docs.python.org/3/library/exceptions.html#exception-hierarchy

1.2 捕获多个异常的方法:三种格式

try:
    num1 = 0
    num2 = 5
    result = num2/num1
    num3 = 'a'
    result = num3/num1
    print('try的最后一条code')
# 捕获多个异常方法1
# except ZeroDivisionError as e:
#     print('ZeroDivisionError:',e)
# except TypeError as e:
#     print('TypeError:',e)
# except ValueError as e:
#     print("ValueError")
# except UnicodeError as e: # 永远捕获不到UnicodeError,因为UnicodeError是ValueError的子类
#     print("UnicodeError")
# 捕获多个异常方法2
# except (TypeError, ZeroDivisionError) as e:
#     print('捕获多个异常\n',e)
# 捕获多个异常方法3
except BaseException as e:
    print('except:',e)
    
else:
    print('try内code没异常会执行else')
    
finally:
    print('try内code有无异常都会执行finally')

1.3 自定义异常类

#自定义异常类
#注意点定义类必须继承 Exception 否则无法抛出异常

class CustonException(Exception):
    def __init__(self,content):
        print(content)
        print("你太老了")
content = input("请输入你的年龄:")
if int(content) > 25:
    #抛出自定义异常
    raise CustomException(content)

2 模块

  • 模块定义:通俗理解一个py文件就是一个模块,模块的功能:管理功能代码
  • 可以定义类,可以定义函数,可以定义全局变量,执行对应的代码操作

2.1 内置模块:python自己的模块,如:sys,time,random

# 内置模块:
import random # 生成随机数
result = random.random() #[0,1)  ==》0.4811445824444963
# randint(a,b) #[a,b]
print(result)

import time
time.sleep(5) #时间停制

2.2 自定义模块

2.2.1 自定义模块Python_FirstModule.py

# 自定义模块Python_FirstModule.py  特别注意是要.py格式
# 定义全局变量
my_num = 110
# 定义f
def show():
    print("我是一个函数f")

# 定义一个类
class Student(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def show_method_in_class(self):
        print(self.name)
        print(self.age)

2.2.2 导入自定义模块

① 模块的功能代码使用:全局变量,函数,类
② 查看模块名
# 自定义模块
import Python_FirstModule as PY_fm
print(PY_fm.my_num)
PY_fm.show()

# 使用模块中的 Student类
s = PY_fm.Student('Jsir',25)
s.show_method_in_class()

# 查看模块名:
print(__name__) # 在里面永远是==> __main__
print(Python_FirstModule) # 路径

2.3 导入模块:三种导入方式+更改别名(有个坑)

# 1:import 模块名
# 【更改别名】import 模块名 as 别名
import Python_FirstModule as fm
# 2:from 模块名 import 功能代码
from Python_FirstModule import my_num
from Python_FirstModule import Student
from Python_FirstModule import show
from Python_FirstModule import show as fm_show
s = Student("Jsir",24)
s.show_method_in_class()
show()
my_num

#----------------------有坑分界线--------------------------------------------
# **有坑:如果当前模块有和第三方模块重名的函数,那么第三方模块会被覆盖
def show():
    print('当前模块下的函数')
show()
fm_show()

# 3:from 模块名 import *   导入所有功能代码
作业

#第一个作业:不同路径的py如何导入
#第二个作业: 网络查询这句代码的意思:并描述应用场景
if name == “main”:

3 包

  • 定义:包通俗理解就是一个文件夹,只不过里面有一个__init__.py文件,包 是管理模块的,模块是管理功能代码的
    first_package【包】
    -------__init__.py
    -------first.py【模块】
    -------second.py【模块】
#----import导入包里面的模块---
import first_package.first

#---import导入包里面的模块设置【别名】-
import first_package.first as one

#----from导入包名import模块名---
from first_package import second

#---from包名.模块名import功能代码
from first_package.first import show #需要保证当前模块没有导入模块的功能代码?

#--- from包名import *,默认不会导入包里面的所有模块,需要在init文件里面使用_a11-去指定导入的模块from first_package import *

__init__文件写法:

#如果外界使用from包名import *不会导入包里面的所有模块,需要使用_al1_指定
__all__=["first", "second"]
#从当前包导入对应的模块
from . import first 
from . import second

4 文件操作

4.1 不同的读取模式+编码

  • 文件是以硬盘为载体,code在内存里
#1.r:只读  #2.w:只写  #3.a:追加
#4.rb:以二进制方式写入
#5.wb:以二进制的方式读取
#6.ab:以二进制的方式追加
#了解:不要使用
#r+ w+ a+ ab+ wb+ rb+
# 设置编码方式:gbk,utf-8
#读取文件:(默认都在当前文件夹里读取)

4.2 读文件

读法1

file = open('文件路径',"打开方式","字符编码")
1.content = file.read()
2.content = file.read(size) 最多读取size个字节内容
3.content = file.readline() 每次读取一行内容
4.content = file.readlines() 一次读取所有内容并按行返回list
file.close()

读法2

with open('文件路径',"打开方式","字符编码") as file:
print(file.read())
 for line in file.readlines():
     print(line.strip()) # 把末尾的\n去掉
#为了兼容不同系统encoding="utf-8"
#------- r模式 ---------
file = open("1.txt","r",encoding="utf-8") # file为操作的对象
content = file.read()#读取文件中所有的数据
print(content)
file.close()#关闭文件
#------- w模式 ---------
#【如果文件不存在】,会帮助我们创建文件(在默认文件夹下)
#第二次运行会【覆盖】之前的数据
file = open("1.txt","w",encoding="utf-8")
file.write("hhh")
file.write("eee")
file.write("hhh")
file.write("hhh")
file.write("hhh")
file.close()
#------ a模式 ---------
file = open("1.txt","a",encoding="utf-8")
file.write("aaa")
file.close()

#以二进制方式读取rb--------------
#binary mode doesn't take an encoding argument
#如果是二进制方式不需要指定编码格式(帮助我们自动编码)
#hello --->utf-8 --->二进制的数据
file = open("1.txt","rb")
content = file.read()
print(content) # ==>b'123abc'
#b"代表是二进制数据 将二进制数据=>成字符串数据(解码)
content = content.decode("utf-8") # 解码
print(content) # ==>123abc
file.close()

#-----二进制写入的方式wb-----
file = open("1.txt","wb")
#写入的数据必须是二进制
#将 哈哈(str)--->二进制写入(编码)
content = "哈哈"
file_data = content.encode("utf-8") # 编码[字符串数=>二进制数据]
file.write(file_data)
file.close()

#以二进制追加数据ab---------
file = open("1.txt","ab") 
content = "haha"
content = content.encode("utf-8")
file.write(content)
file.close()

# r+ 支持读写 -----------------
# 文件的局限性:存取小批量数据
# 只要没看见b就添加encoding
file =  open("1.txt","r+",encoding="utf-8")
# content = file.read() # 读
# print(content)
file.write("aaa") # 写 写在文件前,不覆盖
file.close()

作业:

encoding encode 查询一下区别
文件的赋值:将1.txt里面的文件 copy 2.txt里面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值