python之异常处理实例及加密

python异常处理实例记录,简单一个例子来说明异常处理的使用方式,简单做下笔记

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class FileNotFoundException(Exception):
def __init__(self):
self.code = 1001
self.msg = '文件不存在'

class ContentNotFoundException(Exception):
def __init__(self):
self.code = 1002
self.msg = '查询结果为空'

class KeyEmptyException(Exception):
def __init__(self):
self.code = 1003
self.msg = '关键词不能为空'

import os
def search_str(file, key):
try:
if not os.path.exists(file):
raise FileNotFoundException()
if key == '':
raise KeyEmptyException()
with open(file, mode='r', encoding='utf8') as f:
for line in f:
if line.startswith(key):
print('找到了,',line)
break
else:
raise ContentNotFoundException()

except FileNotFoundException as e:
print(e.code, e.msg)
except ContentNotFoundException as e:
print(e.code, e.msg)
except KeyEmptyException as e:
print(e.code, e.msg)
except Exception as e:
print(e)
search_str('aaa.text', 'ddd')

python MD5加密:

python中md5加密需要引入一个模块hashlib

1
2
3
4
5
6
hashlib
obj = hashlib.md5()
obj.update(.encode())
v = obj.hexdigest()

(objv)