-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileProcess.py
More file actions
100 lines (85 loc) · 2.83 KB
/
fileProcess.py
File metadata and controls
100 lines (85 loc) · 2.83 KB
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
import os
import shutil
class FileProcess:
@staticmethod
def init_file(paths):
try:
directory = os.path.dirname(paths)
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.exists(paths):
with open(paths,"w"):
pass
# 创建文件
except:
print(">文件初始化异常")
@staticmethod
def setKeyValue(path,new_key, new_value):
# print(f"key:{new_key},value:{new_value}")
FileProcess.init_file(path)
lines = []
# try:
with open(path,'r+',encoding='utf8') as files:
isnew = True
for line in files:
if len(line.strip()) != 0:
key, value = line.strip().split('=')
if key == new_key:
new_line = f"{key}={new_value}"
isnew = False
# print(f'写入成功:{new_line}')
else:
new_line = line
# print(f"new_line:{new_line}")
lines.append(new_line)
if isnew is True:
new_line = f"{new_key}={new_value}"
lines.append(new_line)
return FileProcess.writeData(path,lines)
@staticmethod
# 键值对数据写入写入
def writeData(path,lines):
# try:
file = open(path,"w",encoding='utf8')
for i in lines:
if not i.endswith('\n'):
i += '\n'
# print(f"i:{i}")
file.write(i)
file.close()
return True
@staticmethod
def delPath(del_path):
try:
if os.path.isfile(del_path):
# 删除文件
os.remove(del_path)
elif os.path.isdir(del_path):
# 删除目录
if os.listdir(del_path): # 如果目录非空
shutil.rmtree(del_path)
else:
os.rmdir(del_path)
else:
print(f">文件不存在{del_path}")
except Exception as e:
print(f">异常: {e}")
@staticmethod
def getKeyValue(find_path, find_key):
try:
with open(find_path, 'r+',encoding='utf8') as files:
for line in files:
# print(f"{line}")
key, value = line.strip().split('=')
# print(f"{key},{find_key}")
if key == find_key:
return value
return False
except:
return False
if __name__ == '__main__':
path = "User Settings/config.txt"
file = FileProcess().setKeyValue(path,'api_key','5')
file2 = FileProcess().getKeyValue(path,'prompt')
# print(file)
# print(file2)