文件和异常

文件

文件操作很简单就是一个open函数,但是我们需要先了解一下打开权限的问题

权限

操作模式 具体含义
r 读权限
w 写权限(会更新内容)
x 文件存在就会抛出异常
a 追加模式
b 二进制模式
t 文本模式
+ 更新(可读可写)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ?文件操作学习请注意

# 首先创建一个文本,我们使用'w'模式没有的话就会创建一个

with open("wxLearn.txt", "w") as f:
# 没有的话就会创建一个
inputStr = "wxLearn"
f.write(inputStr)
# !这样使用会自动close

# 普通的使用方法
f = open("wxLearn.txt", "r")
outputStr = f.readline()
print(outputStr)
f.close() # !一定要close

异常

利用异常编写出base64

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import base64
from abc import abstractclassmethod, ABCMeta


class EnAndDecode(metaclass=ABCMeta):
def __init__(self) -> None:
pass

@abstractclassmethod
def decode():
pass

@abstractclassmethod
def encode():
pass


class Base64(EnAndDecode):
def __init__(self) -> None:
super().__init__()

@staticmethod
def encode(string) -> str:
try:
base64_bytes = string.encode("utf-8")
answer = base64.b64encode(base64_bytes)
return answer.decode("utf-8")
except Exception as e:
# 当运行出错
print(e)

@staticmethod
def decode(string) -> str:
try:
base64_bytes = string.encode("utf-8")
answer = base64.b64decode(base64_bytes)
return answer.decode("utf-8")
except Exception as e:
print(e)

@staticmethod
def encode_n(string, n):
for i in range(n):
try:
base64_bytes = string.encode("utf-8")
answer = base64.b64encode(base64_bytes)
string = answer.decode("utf-8")
except Exception as e:
print(e)
return string

@staticmethod
def decode_n(string):
count = 0
while True:
try:
base64_bytes = string.encode("utf-8")
string = base64.b64decode(base64_bytes)
string = string.decode("utf-8")
count += 1
except Exception as e:
return string, count


def menu():
print(
"""
1. base64加密
2. base64解密
3. base64加密n次
4. base64解密n次"""
)


def getOption():
while True:
option = input("你的选择是什么?:")
try:
option = int(option)
if option in [1, 2, 3, 4]:
return option
else:
print("请输入正确的选项")
except Exception as e:
print("请输入正确的选项")


if __name__ == "__main__":
# 菜单
menu()
# 选项
option = getOption()

if option == 1:
string = input("请输入你要加密的内容:")
print(Base64.encode(string))
elif option == 2:
string = input("请输入你要解密的内容:")
print(Base64.decode(string))
elif option == 3:
string = input("请输入你要加密的内容:")
n = int(input("你要加密几次?:")) # !这里可以做类型检查
print(Base64.encode_n(string, n))
elif option == 4:
string = input("请输入你要解密的内容:")
answer,count=Base64.decode_n(string)
print(f"你的密文一共加密{count}次,结果是:{answer}")


文件和异常
https://tsy244.github.io/2023/10/19/python/文件和异常/
Author
August Rosenberg
Posted on
October 19, 2023
Licensed under