0
0
Fork 0

完成对open函数的包装,且封装成工具类

Bug499-WangZiming
王梓铭 2022-11-21 20:00:30 +08:00
parent 415ac25a31
commit b8560a34e6
1 changed files with 46 additions and 0 deletions

46
app/file_open.py Normal file
View File

@ -0,0 +1,46 @@
import os
class ModeErrorException(Exception):
def __init__(self, error_info):
super().__init__(self)
self.error_info = error_info
def __str__(self):
return self.error_info
class FileOpen:
def __init__(self):
pass
@staticmethod
def read_only(path, mode='r'):
if mode not in ['r', 'r+', 'rb', 'rt', 'rb+', 'rt+']:
raise ModeErrorException('the input mode is wrong')
my_dir = os.path.dirname(path) # 获得路径的目录
if not os.path.exists(my_dir): # 判断文件的所有父文件夹是否存在
os.makedirs(my_dir) # 创建所有父文件夹
# 读文件需要判断文件是否存在,不存在则创建
if not os.path.exists(path):
open(path, mode)
return open(path, mode)
@staticmethod
def write_able(path, mode='w'):
if mode not in ['w', 'w+', 'wb', 'wt', 'wb+', 'wt+']:
raise ModeErrorException('the input mode is wrong')
my_dir = os.path.dirname(path) # 获得路径的目录
if not os.path.exists(my_dir): # 判断文件的所有父文件夹是否存在
os.makedirs(my_dir) # 创建所有父文件夹
return open(path, mode)
if __name__ == "__main__":
wf = FileOpen.write_able(r"D:\Workspace\gitcode\EnglishPal\app\static\test.txt")
wf.write("asdasdasd")
wf.close()
rf = FileOpen.read_only(r"D:\Workspace\gitcode\EnglishPal\app\static\test.txt")
for line in rf.readlines():
print(line)