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

yipeiwu_com6年前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学生成绩管理系统简洁版

讲起学生成绩管理系统,从大一C语言的课程设计开始,到大二的C++课程设计都是这个题,最近在学树莓派,好像树莓派常用Python编程,于是学了一波Python,看了一点基本的语法想写点东西...

pytorch实现对输入超过三通道的数据进行训练

案例背景:视频识别 假设每次输入是8s的灰度视频,视频帧率为25fps,则视频由200帧图像序列构成.每帧是一副单通道的灰度图像,通过pythonb里面的np.stack(深度拼接)可将...

Python使用PDFMiner解析PDF代码实例

Python使用PDFMiner解析PDF代码实例

近期在做爬虫时有时会遇到网站只提供pdf的情况,这样就不能使用scrapy直接抓取页面内容了,只能通过解析PDF的方式处理,目前的解决方案大致只有pyPDF和PDFMiner。因为据说P...

Python通过OpenCV的findContours获取轮廓并切割实例

1 获取轮廓 OpenCV2获取轮廓主要是用cv2.findContours import numpy as np import cv2 im = cv2.imread('test...

在Python中处理日期和时间的基本知识点整理汇总

在Python中处理日期和时间的基本知识点整理汇总

 Python程序可以处理多种方式的日期和时间。日期格式之间的转换是一种常见计算机的杂活。 Python的时间和日历模块,能帮助处理日期和时间。 Tick是什么? 时间...