2022-11-21 20:00:30 +08:00
|
|
|
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
|
2022-11-21 22:38:46 +08:00
|
|
|
def read_only(path, mode='r', encoding=None):
|
2022-11-21 20:00:30 +08:00
|
|
|
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):
|
2022-11-22 19:19:00 +08:00
|
|
|
f = open(path, 'w', encoding)
|
|
|
|
f.close()
|
|
|
|
return open(path, mode=mode, encoding=encoding)
|
2022-11-21 20:00:30 +08:00
|
|
|
|
|
|
|
@staticmethod
|
2022-11-21 22:38:46 +08:00
|
|
|
def write_able(path, mode='w', encoding=None):
|
2022-11-21 20:00:30 +08:00
|
|
|
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) # 创建所有父文件夹
|
2022-11-22 19:19:00 +08:00
|
|
|
return open(path, mode=mode, encoding=encoding)
|
2022-11-21 20:00:30 +08:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-11-22 21:26:06 +08:00
|
|
|
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)
|