From b8560a34e6b08d175ca72c19726e8c43bef0f0db Mon Sep 17 00:00:00 2001 From: torch <178428409@qq.com> Date: Mon, 21 Nov 2022 20:00:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=AF=B9open=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E7=9A=84=E5=8C=85=E8=A3=85=EF=BC=8C=E4=B8=94=E5=B0=81?= =?UTF-8?q?=E8=A3=85=E6=88=90=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/file_open.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 app/file_open.py diff --git a/app/file_open.py b/app/file_open.py new file mode 100644 index 0000000..ee5512a --- /dev/null +++ b/app/file_open.py @@ -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) \ No newline at end of file