异常
'''
try:
可能出现异常的代码
except:
若出现异常执行的代码
'''
try:
f = open("D:/linux.txt", "r", encoding="utf-8")
f.readlines()
except:
print("出现异常了,文件不存在,更换模式w")
# f = open("D:/linux.txt", "w", encoding="utf-8")
捕获指定异常
'''
try:
print(name)
except NameError as e:
print('name变量名未定义错误')
'''
try:
print(name)
except NameError as e:
print(e)
捕获多个异常
'''
try:
print(1/0)
except (NameError, ZeroDivisionError):
print('name变量名未定义错误')
'''
try:
print(1 / 0) # 先捕获
print(name)
except (NameError, ZeroDivisionError) as e:
print(e)
捕获所有异常
try:
print(age)
except Exception as e:
print(e)
异常else
try:
print(1)
except Exception as e:
print(e)
else:
print("执行else语句,无异常")
finally:无论有无异常都会执行此语句
try:
print(gender)
except Exception as e:
print(e)
else:
print("执行else语句,无异常")
finally:
print("有无异常都执行finally语句")
包机制
此写法表示本文件可执行,导包调用模块时不执行
if __name__ == "__main__":
print(1)
打开控制台,指令:pip install 包名
import numpy as np # 科学计算
e = np.e
print(e)
import pandas as pd # 数据分析
案例
包结构
模块str_util
# 字符串工具
def str_reverse(s):
"""
字符串反转
:param s:原字符串
:return: 反转后字符串
"""
return s[::-1]
def substr(s, x, y):
"""
字符串切片
:param s:传入字符串
:param x: 下标
:param y: 下标
:return: 被切片字符串
"""
return s[x:y]
if __name__ == '__main__':
print(f"字符串逆转后:{str_reverse('java')}")
print(f"字符串切片后:{substr('java', 0, 3)}")
测试
模块file_util
# 文件处理工具
def print_file_info(file_name):
"""
读文件内容输出控制台
:param file_name: 文件路径
:return: None
"""
f = None
try:
f = open(file_name, "r", encoding="utf-8")
# lines = f.readlines()
content = f.read()
print(content)
except Exception as e:
print(f"异常:{e}")
finally:
if f: # 若文件不存在,f=None,if语句中,None表示False,则不会执行f.close();若文件存在,if f为True,则顺利执行f.close()
f.close()
def append_to_file(file_name, data):
"""
向文件追加内容
:param file_name:文件路径
:param data: 追加内容
:return: None
"""
f = open(file_name, "a", encoding="utf-8")
f.write(data)
f.close()
if __name__ == '__main__':
print_file_info("D:/bill.txt33")
append_to_file("D:/append.txt", "\naaaabvbbbvvvv")
print_file_info("D:/append.txt")
测试
注意导包及其调用方法
str1 = my_utils.str_util.str_reverse('TENET')
print("逆转字符串'TENET':", str1)
str2 = my_utils.str_util.substr('123344556', 3, 6)
print("截串:", str2)
print("文件不存在,异常:")
my_utils.file_util.print_file_info("D:/ttt.txt")
print("追加:")
my_utils.file_util.append_to_file("D:/append.txt", "\t追加:塞尔达传说")
print("文件存在,输出文件内容:")
my_utils.file_util.print_file_info("D:/append.txt")