#-*-coding:utf-8-*-#写入数据的工具类 class FileManager (object): #保存文件名称 filename = ' student.txt ' #写一个写入数据的接口 @c Lassmethod def write (CLS, content, split = ' \ n '): ":p Aram Content: Data to be written:p Aram split: Each piece of data
Separator Between: return: ' #判断传入的参数是否为字符串类型, if yes, write data, if not then throw exception if isinstance (content, str): #打开文件 f = open (Cls.filename, ' a ') #写入数据 f.write (content) F.write (sp
Lit) #关闭文件 f.close () else:raise typeerror (' content must be a str! ') #写入多行数据 @classmethod def writelines (CLS, str_list, split= ' \ n '): rs = isinstance (str_list, list) # Determines whether an object is a type and returns true if it does not return FALSE if Rs: #遍历列表, remove each data, and determine whether the data type is a string for content in Str_li
ST: #如果不是字符串类型 if isinstance (content, str) = = False: #抛出异常 Raise TypeError (' str_list must be a list of Str!,such as:[str1,str2,...] ') #如果没抛出异常, you can write data F = open (Cls.filename, ' a ') string =split.join (str_list) f.write (stri ng) F.close () Else: #如果不是列表, throwing an exception raise TypeError (' str_list must be a list of s
TR,EX[STR1, str2,...] #只有在当前文件直接执行时, the following code is executed if __name__ = = ' __main__ ': filemanager.filename = ' all_student.txt ' Filemanager.write (' Hell O ') filemanager.write (' World ') filemanager.writelines ([' Hello ', ' world ', ' hello ', ' python '])