Python实现的tab文件操作类分享
类代码:
#-*-coding:gbk-*- importos classTABFILE: def__init__(self,filename,dest_file=None): self.filename=filename ifnotdest_file: self.dest_file=filename else: self.dest_file=dest_file self.filehandle=None self.content=[] self.initflag=False self.column=0 self.row=0 self.data=[] defInit(self): try: self.filehandle=open(self.filename,'r') self.initflag=self._load_file() except: pass else: self.initflag=True returnself.initflag defUnInit(self): ifself.initflag: self.filehandle.close() def_load_file(self): ifself.filehandle: self.content=self.filehandle.readlines() self.row=len(self.content)-1 head=self.content[0].split('\t') self.column=len(head) forlineinself.content: #这里需要去掉末尾的换行 #line=line-'\n\r' self.data.append(line.rstrip().split('\t')) returnTrue else: returnFalse defGetValue(self,row,column): if0<row<self.rowand0<column<self.column: returnself.data[row][column-1] else: returnNone defSetValue(self,row,column,value): if0<row<self.rowand0<column<self.column: self.data[row][column]=value else: returnFalse defSaveToFile(self): filewrite=open(self.dest_file,'w') ifnotfilewrite: returnFalse sep_char='\t' forlineinself.data: filewrite.write(sep_char.join(line)+'\n') filewrite.close() returnTrue