Python实现的tab文件操作类分享

yipeiwu_com5年前Python基础

类代码:

# -*- coding:gbk -*-

import os

class TABFILE:
  def __init__(self, filename, dest_file = None):
    self.filename = filename
    if not dest_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 = []
  def Init(self):
    try: 
      self.filehandle = open(self.filename, 'r')
      self.initflag = self._load_file()
    except: 
      pass
    else:
      self.initflag = True
    return self.initflag

  def UnInit(self):
    if self.initflag:
      self.filehandle.close()
    
  def _load_file(self):
    if self.filehandle:
      self.content = self.filehandle.readlines()
      self.row = len(self.content) - 1
      head = self.content[0].split('\t')
      self.column = len(head)
      for line in self.content:
        #这里需要去掉末尾的换行
        #line = line - '\n\r'
        self.data.append(line.rstrip().split('\t'))
      return True
    else:
      return False

  def GetValue(self, row, column):
    if 0 < row < self.row and 0 < column < self.column:
      return self.data[row][column - 1]
    else:
      return None

  def SetValue(self, row, column, value):
    if 0 < row < self.row and 0 < column < self.column:
      self.data[row][column] = value
    else:
      return False

  def SaveToFile(self):
    filewrite = open(self.dest_file, 'w')
    if not filewrite:
      return False
    sep_char = '\t'
    for line in self.data:
      filewrite.write(sep_char.join(line)+'\n')
    filewrite.close()
    return True

相关文章

pyqt5 禁止窗口最大化和禁止窗口拉伸的方法

如下所示: 在def __init__(self):函数里添加 self.setFixedSize(self.width(), self.height()) 以上这篇pyqt5 禁止窗口...

详解Python匿名函数(lambda函数)

匿名函数lambda Python使用lambda关键字创造匿名函数。所谓匿名,意即不再使用def语句这样标准的形式定义一个函数。这种语句的目的是由于性能的原因,在调用时绕过函数的栈分配...

Python+OpenCV+图片旋转并用原底色填充新四角的例子

我就废话不多说了,直接上代码吧! import cv2 from math import fabs, sin, cos, radians import numpy as np fro...

Django 过滤器汇总及自定义过滤器使用详解

Django 过滤器 过滤器 描述 示例 upper 以大写方式输出 {...

Windows下使Python2.x版本的解释器与3.x共存的方法

Python2 和 Python3 是不兼容的,如果碰到无法升级到 Python2 代码,或者同事中有坚守 Python2 阵营的情况,就要考虑 Python2 和 Python3 在系...