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

相关文章

使用python实现ANN

使用python实现ANN

本文实例为大家分享了python实现ANN的具体代码,供大家参考,具体内容如下 1.简要介绍神经网络 神经网络是具有适应性的简单单元组成的广泛并行互联的网络。它的组织能够模拟生物神经系统...

Python深度优先算法生成迷宫

本文实例为大家分享了Python深度优先算法生成迷宫,供大家参考,具体内容如下 import random #warning: x and y confusing sx...

Python操作Oracle数据库的简单方法和封装类实例

本文实例讲述了Python操作Oracle数据库的简单方法和封装类。分享给大家供大家参考,具体如下: 最近工作有接触到Oracle,发现很多地方用Python脚本去做的话,应该会方便很多...

python实现中文输出的两种方法

本文实例讲述了python实现中文输出的两种方法。分享给大家供大家参考。具体如下: 方法一: 用encode和decode 如: import os.path import xlrd...

Python利用matplotlib绘制约数个数统计图示例

Python利用matplotlib绘制约数个数统计图示例

本文实例讲述了Python利用matplotlib绘制约数个数统计图。分享给大家供大家参考,具体如下: 利用Python计算1000以内自然数的约数个数,然后通过matplotlib绘制...