目录
3.ZeroDivisionError:除数为 0 错误(零除错误)
一.异常的处理过程
python 中一切都是对象,异常也采用对象的方式来处理。处理过程:
1. 抛出异常:在执行一个方法时,如果发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给解释器。
2. 捕获异常:解释器得到该异常后,寻找相应的代码来处理该异常。
二.异常处理结构
1.try...一个 except 结构
while True:
try:
x = int(input("请输入一个数字:"))
print("您入的数字是",x)
if x==88:
print("退出程序")
break
except:
print("异常:输入的不是一个数字")
执行结果:
请输入一个数字:10
您入的数字是 10
请输入一个数字:abc
异常:输入的不是一个数字
请输入一个数字:88
您入的数字是 88
退出程序
2.try...多个 except 结构
try:
a = input("请输入被除数:")
b = input("请输入除数:")
c = float(a)/float(b)
print(c)
except ZeroDivisionError:
print("异常:除数不能为 0")
except TypeError:
print("异常:除数和被除数都应该为数值类型")
except NameError:
print("异常:变量不存在")
except BaseException as e:
print(e)
print(type(e))
执行结果:
请输入被除数:10
请输入除数:0
异常:除数不能为 0
3.try...except...else 结构
try:
a = input("请输入被除数:")
b = input("请输入除数:")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print("除的结果是:",c)
发生异常的执行情况(执行 except 块,没有执行 else):
请输入被除数:5
请输入除数:0
float division by zero
没有发生异常的执行情况(执行完 try 块后,执行 else):
请输入被除数:10
请输入除数:5
除的结果是: 2.0
4.try...except...finally 结构
try:
a = input("请输入一个被除数:")
b = input("请输入一个除数:")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print("我是 finally 中的语句,无论发生异常与否,都执行!")
print("程序结束!")
执行结果如下:
请输入被除数:10
请输入除数:0
float division by zero
我是 finally 中的语句,无论是否发生异常都执行
5.return 语句和异常处理问题
def test01():
print("step1")
try:
x = 3/0
# return "a"
except:
print("step2")
print("异常:0 不能做除数")
#return "b"
finally:
print("step4")
#return "d"
print("step5")
return "e" #一般不要将 return 语句放到 try、except、else、 finally 块中,会发生一些意想不到的错误。建议放到方法最后。
print(test01())
执行结果:
step1
step2
异常:0 不能做除数
step4
step5
e
三.常见异常的解决
1.SyntaxError:语法错误
int a = 3
int a =3
^
SyntaxError: invalid syntax
2.NameError:尝试访问一个没有申明的变量
print(a)
print(a)
NameError: name 'a' is not defined
3.ZeroDivisionError:除数为 0 错误(零除错误)
a = 3/0
a = 3/0
ZeroDivisionError: division by zero
4.ValueError:数值错误
float("gaoqi")
float("gaoqi")
ValueError: could not convert string to float: 'gaoqi'
5.TypeError:类型错误
123+"abc"
123+"abc"
TypeError: unsupported operand type(s) for +: 'int' and 'str
6.AttributeError:访问对象的不存在的属性
a=100
a.sayhi()
a.sayhi()
AttributeError: 'int' object has no attribute 'sayhi'
7.IndexError:索引越界异常
a = [4,5,6]
a[10]
a[10]
IndexError: list index out of range
8.KeyError:字典的关键字不存在
a = {'name':"gaoqi",'age':18}
a['salary']
a['salary']
KeyError: 'salary'
四.with 上下文管理
不论何种原因跳出 with 块,不论是否有异常,总能保证资源正常释放。
with open("d:/bb.txt") as f:
for line in f:
print(line)
执行结果:
gaoqi
sxt
baizhan
五.trackback 模块
1.使用 Traceback 模块打印异常信息
import traceback
try:
print("step1")
num = 1/0
except:
traceback.print_exc()
2.使用 traceback 将异常信息写入日志文件
import traceback
try:
print("step1")
num = 1/0
except:
with open("d:/a.log","a") as f:
traceback.print_exc(file=f)
六.自定义异常类
class AgeError(Exception): #继承 Exception
def __init__(self,errorInfo):
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return str(self.errorInfo)+",年龄错误!应该在 1-150 之间"
############测试代码################
if __name__ == "__main__":
#如果为 True,则模块是作为独立文件运行,可以执行测试代码
age = int(input("输入一个年龄:"))
if age<1 or age>150:
raise AgeError(age)
else:
print("正常的年龄:",age)
执行结果如下:
输入一个年龄:200
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/mypro_exception/my10.py", line 16, in <module>
raise AgeError(age)
__main__.AgeError: 200,年龄错误!应该在 1-150 之间
七.文本文件和二进制文件
1.文本文件
是普通“字符”文本。
2.二进制文件
MP4 视频文件、MP3 音频文件、JPG 图片、doc 文档等等。
八.创建文件对象 open()
f = open(r"d:\b.txt","w")
r
读 read 模式
w
写 write 模式。如果文件不存在则创建;如果文件存在,则重写新内容;
a
追加 append 模式。如果文件不存在则创建;如果文件存在,则在文件末尾追加内容
b
二进制 binary 模式(可与其他模式组合使用)
+
读、写模式(可与其他模式组合使用)
如果我们没有增加模式“b”,则默认创建的是文本文件对象,处理的基本单元是“字符”。如果是二进制模式“b”,则创建的是二进制文件对象,处理的基本单元是“字节”。
八.基本的文件写入操作
f = open(r"a.txt","a")
s = "itbaizhan\nsxt\n"
f.write(s)
f.close()
九.write()/writelines()写入数据
write(a):把字符串 a 写入到文件中
writelines(b):把字符串列表写入文件中,不添加换行符
f = open(r"d:\bb.txt","w",encoding="utf-8")
s = ["高淇\n","高老三\n","高老四\n"]
f.writelines(s)
f.close()
十.close()关闭文件流
1.结合异常机制 finally 确保关闭文件对象
try:
f = open(r"my01.txt","a")
str = "gaoqi"
f.write(str)
except BaseException as e:
print(e)
finally:
f.close()
2.with 语句(上下文管理器)
s = ["高淇\n","高老三\n","高老五\n"]
with open(r"d:\bb.txt","w") as f:
f.writelines(s)
十一.文本文件的读取
1. read([size])
从文件中读取 size 个字符,并作为结果返回。如果没有 size 参数,则读取整个文件。
with open(r"bb","r",encoding="utf-8") as f:
print(f.read(4))
或者
with open(r"d:\bb.txt","r") as f:
print(f.read())
2.readline()
读取一行内容作为结果返回。
with open(r"bb.txt","r") as f:
while True:
fragment = f.readline()
if not fragment:
break
else:
print(fragment,end="")
3. readlines()
文本文件中,每一行作为一个字符串存入列表中,返回该列表
with open("e.txt","r",encoding="utf-8") as f:
lines = f.readlines()
lines = [ line.rstrip()+" #"+str(index+1)+"\n" for index,line in enumerate(lines)] #推导式生成列表
with open("e.txt","w",encoding="utf-8") as f:
f.writelines(lines)
4.使用迭代器
(每次返回一行,返回所有行)读取文本文件
with open(r"d:\bb.txt","r") as f:
for a in f:
print(a,end="")
十二.二进制文件的读取和写入
f = open(r"d:\a.txt", 'wb')
#可写的、重写模式的二进制文件对象
f = open(r"d:\a.txt", 'ab')
#可写的、追加模式的二进制文件对象
f = open(r"d:\a.txt", 'rb')
#可读的二进制文件对象
with open('aa.gif', 'rb') as f:
with open('aa_copy.gif', 'wb') as w:
for line in f.readlines():
w.write(line)
print('图片拷贝完成')
十三.文件任意位置操作
seek()移动文件指针示例
seek(offset,[whence])
把文件指针移动到新的位置,offset 表示相对于 whence 的多少个字节的偏移量;
offset:off 为正往结束方向移动,为负往开始方向移动
whence 不同的值代表不同含义:
0: 从文件头开始计算(默认值)
1:从当前位置开始计算
2:从文件尾开始计算
with open("e.txt","r",encoding="utf-8") as f:
print("文件名是:{0}".format(f.name))
print(f.tell())
print("读取的内容:{0}".format(str(f.readline())))
print(f.tell())
f.seek(0,0)
print("读取的内容:{0}".format(str(f.readline())))
十四.使用 pickle 序列化
pickle.dump(obj, file)
obj 就是要被序列化的对象,file 指的是存储的文件
pickle.load(file)
从 file 读取数据,反序列化成对象
import pickle
with open(r"d:\data.dat","wb") as f:
a1 = "高淇"
a2 = 234
a3 = [20,30,40]
pickle.dump(a1,f)
pickle.dump(a2, f)
pickle.dump(a3, f)
with open(r"d:\data.dat","rb") as f:
a1 = pickle.load(f)
a2 = pickle.load(f)
a3 = pickle.load(f)
print(a1)
print(a2)
print(a3)
执行结果:
高淇
234
[20, 30, 40]
十五.CSV 文件的操作
1.csv.reader 对象和 csv 文件读取
import csv
with open(r"d:\a.csv") as a:
a_csv = csv.reader(a) #创建 csv 对象,它是一个包含所有数据的列表,每一行为一个元素
headers = next(a_csv) #获得列表对象,包含标题行的信息
print(headers)
for row in a_csv: #循环打印各行内容
print(row)
2.csv.writer 对象和 csv 文件写入
import csv
headers = ["工号","姓名","年龄","地址","月薪"]
rows = [("1001","高淇",18,"西三旗 1 号院","50000"),("1002","高八",19,"西三旗 1 号院","30000")]
with open(r"d:\b.csv","w") as b:
b_csv = csv.writer(b) #创建 csv 对象
b_csv.writerow(headers) #写入一行(标题)
b_csv.writerows(rows) #写入多行(数据)
十六.os 和 os.path 模块
1.os 模块-调用操作系统命令
import os
os.system("ping www.baidu.com")
import os
os.startfile(r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe")
2.os 模块-文件和目录操作
listdir(path)
返回 path 目录下的文件和目录列表
#coding=utf-8
#测试 os 模块中,关于文件和目录的操作
import os
#############获取文件和文件夹相关的信息################
print(os.name) #windows->nt linux 和 unix->posix
print(os.sep) #windows->\ linux 和 unix->/
print(repr(os.linesep)) #windows->\r\n linux-->\n\
print(os.stat("my02.py"))
##############关于工作目录的操作###############
#print(os.getcwd())
#os.chdir("d:") #改变当前的工作目录为:d:盘根目录
#os.mkdir("书籍")
################创建目录、创建多级目录、删除#############
#os.mkdir("书籍")
#os.rmdir("书籍") #相对路径都是相对于当前的工作目录
#os.makedirs("电影/港台/周星驰")
#os.removedirs("电影/港台/周星驰") #只能删除空目录
#os.makedirs("../音乐/香港/刘德华") #../指的是上一级目录
#os.rename("电影","movie")
#print(os.getcwd())
dirs = os.listdir("movie")
print(dirs)
#############################
3.os.path 模块
os.path 模块提供了目录相关(路径判断、路径切分、路径连接、文件夹遍历)的操作
import os
import os.path
#################获得目录、文件基本信息
######################
print(os.path.isabs("d:/a.txt"))
#是否绝对路径
print(os.path.isdir("d:/a.txt")) #是否目录
print(os.path.isfile("d:/a.txt")) #是否文件
print(os.path.exists("a.txt")) #文件是否存在
print(os.path.getsize("a.txt")) #文件大小
print(os.path.abspath("a.txt")) #输出绝对路径
print(os.path.dirname("d:/a.txt")) #输出所在目录
########获得创建时间、访问时间、最后修改时间##########
print(os.path.getctime("a.txt")) #返回创建时间
print(os.path.getatime("a.txt")) #返回最后访问时间
print(os.path.getmtime("a.txt")) #返回最后修改时间
################对路径进行分割、连接操作####################
path = os.path.abspath("a.txt") #返回绝对路径
print(os.path.split(path)) #返回元组:目录、文件
('C:\\Users\\Administrator\\PycharmProjects\\mypro_io\\test_os', 'a.txt')
print(os.path.splitext(path)) #返回元组:路径、扩展名
('C:\\Users\\Administrator\\PycharmProjects\\mypro_io\\test_os\\a', '.txt')
print(os.path.join("aa","bb","cc")) #返回路径:aa/bb/cc
4.列出指定目录下所有的.py 文件,并输出文件名
import os path=os.getcwd() file_list=os.listdir(path) print(file_list) for filename in file_list: if filename.endswith("py"): print(filename) print("************************") file_list2=[filename for filename in os.listdir(path) if filename.endswith("py")] print(file_list2) for f in file_list2: print(f,end="\t")
十七.walk()递归遍历所有文件和目录
os.walk()方法:
返回一个 3 个元素的元组,
(dirpath, dirnames, filenames),
dirpath:要列出指定目录的路径
dirnames:目录下的所有文件夹
filenames:目录下的所有文件
#coding=utf-8
import os
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
all_files.append(os.path.join(dirpath,dir))
for name in filenames:
all_files.append(os.path.join(dirpath,name))
for file in all_files:
print(file)
十八.shutil 模块(拷贝和压缩)
1.拷贝
import shutil
#copy 文件内容
shutil.copyfile("1.txt","1_copy.txt")
import shutil #"音乐"文件夹不存在才能用。
shutil.copytree("电影/学习","音乐",ignore=shutil.ignore_patterns("*.html","*.htm"))
2.压缩
import shutil
import zipfile
#将"电影/学习"文件夹下所有内容压缩到"音乐 2"文件夹下生成 movie.zip
#shutil.make_archive("音乐 2/movie","zip","电影/学习")
#压缩:将指定的多个文件压缩到一个 zip 文件
#z = zipfile.ZipFile("a.zip","w")
#z.write("1.txt")
#z.write("2.txt")
#z.close()
3.解压缩
import shutil
import zipfile
#解压缩:
z2 = zipfile.ZipFile("a.zip","r")
z2.extractall("d:/") #设置解压的地址
z2.close()
十九.使用递归算法遍历目录下所有文件
import os def getAllFiles(path,level): childFiles=os.listdir(path) for file in childFiles: filepath=os.path.join(path,file) print("\t"*level,filepath) if os.path.isdir(filepath): getAllFiles(filepath,level+1) getAllFiles("小电影",0)