1
0
Fork 0
EnglishPal/app/file_open.py

48 lines
1.6 KiB
Python

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', encoding=None):
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):
f = open(path, 'w', encoding)
f.close()
return open(path, mode=mode, encoding=encoding)
@staticmethod
def write_able(path, mode='w', encoding=None):
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=mode, encoding=encoding)
if __name__ == "__main__":
pass
# 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)