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中PIL安装简单教程

python 的PIL安装是一件很头疼的的事, 如果你要在python 中使用图型程序那怕只是将个图片从二进制流中存盘(例如使用Scrapy 爬网存图),那么都会使用到 PIL 这库,而...

python 判断自定义对象类型

要判断自定义对象的类型,用__class__方法,或者用isinstance(object, class-or-type-or-tuple)-->bool 用__class__不能...

python使用chardet判断字符串编码的方法

本文实例讲述了python使用chardet判断字符串编码的方法。分享给大家供大家参考。具体分析如下: 最近利用python抓取一些网上的数据,遇到了编码的问题。非常头痛,总结一下用到的...

Python 遍历子文件和所有子文件夹的代码实例

Python 遍历子文件和所有子文件夹的代码实例

最近看ECShop到网上找资料,发现好多说明ECShop的文件结构不全面,于是想自己弄个出来。但这是个无聊耗时的工作,自己就写了个Python脚本,可以递归遍历目录下的所有文件和所有子目...

python读取指定字节长度的文本方法

软件版本 Python 2.7.13; Win 10 场景描述 1、使用python读取指定长度的文本; 2、使用python读取某一范围内的文本。 Python代码 test.txt文...