Python实现tab文件操作相关应用方式解读

开发 后端
Python实现tab文件操作在实际应用中是一个比较重要的操作技巧。那么,我们将会在这里通过一段代码示例来为大家详细介绍一下相关操作方法。

Python编程语言的应用范围比较广泛,可以在很多领域中来帮助开发人员实现一些特定的需求。比如在文件操作方面。我们今天就为大家详细介绍一下有Python实现tab文件操作的一些具体操作技巧。

Python实现tab文件操作代码示例:

  1. # -*- coding:gbk -*-  
  2. import os  
  3. class TABFILE:  
  4. def __init__(self, filename, dest_file = None):  
  5. self.filename = filename  
  6. if not dest_file:  
  7. self.dest_file = filename 
  8. else:  
  9. self.dest_file = dest_file  
  10. self.filehandle = None 
  11. self.content = []  
  12. self.initflag = False 
  13. self.column = 0 
  14. self.row = 0 
  15. self.data = []  
  16. def Init(self):  
  17. try:   
  18. self.filehandle = open(self.filename, 'r')  
  19. selfself.initflag = self._load_file()  
  20. except:   
  21. pass  
  22. else:  
  23. self.initflag = True 
  24. return self.initflag  
  25. def UnInit(self):  
  26. if self.initflag:  
  27. self.filehandle.close()  
  28. def _load_file(self):  
  29. if self.filehandle:  
  30. selfself.content = self.filehandle.readlines()  
  31. self.row = len(self.content) - 1  
  32. head = self.content[0].split('\t')  
  33. self.column = len(head)  
  34. for line in self.content:  
  35. #这里需要去掉末尾的换行  
  36. #lineline = line - '\n\r'  
  37. self.data.append(line.rstrip().split('\t'))  
  38. return True  
  39. else:  
  40. return False  
  41. def GetValue(self, row, column):  
  42. if 0 < row < self.row and 0 < column < self.column: 
  43. return self.data[row][column - 1]  
  44. else:  
  45. return None  
  46. def SetValue(self, row, column, value):  
  47. if 0 < row < self.row and 0 < column < self.column: 
  48. self.data[row][column] = value  
  49. else:  
  50. return False  
  51. def SaveToFile(self):  
  52. filewrite = open(self.dest_file, 'w')  
  53. if not filewrite:  
  54. return False  
  55. sep_char = '\t' 
  56. for line in self.data:  
  57. filewrite.write(sep_char.join(line)+'\n')  
  58. filewrite.close()  
  59. return True 

以上就是我们对Python实现tab文件操作的相关介绍。

【编辑推荐】

  1. Python实现ini文件操作基本操作方式分享
  2. Python构造列表基本应用语法详解
  3. 利用PDB实现Python程序调试
  4. Python单元测试正确使用规则
  5. Python SQLITE数据库操作简便易用
责任编辑:曹凯 来源: 博客园
相关推荐

2010-03-03 13:45:08

Python查找重复文

2010-03-04 15:57:23

Python实现ini

2009-12-28 15:00:21

ADO操作

2010-03-04 11:36:02

Python提交表单

2010-03-03 14:30:05

Python set类

2009-12-16 13:33:28

Ruby输出文件信息

2010-03-03 17:33:52

Python读取XML

2010-02-02 17:39:31

C++构造函数

2010-02-05 16:46:58

C++ TinyXml

2010-03-03 15:17:46

Python调用MyS

2009-12-22 10:15:17

ADO.NET规则

2010-03-03 16:40:55

Python HTTP

2010-03-03 13:22:08

Python正则表达式

2010-03-03 13:32:08

Python压缩文件

2010-03-05 10:47:05

Python futu

2010-02-26 13:26:55

WCF消息编码器

2010-03-17 14:42:09

Python 文件

2010-03-23 16:30:47

Python文件复制

2009-12-30 16:45:31

ADO操作

2010-03-22 19:11:55

Python连接
点赞
收藏

51CTO技术栈公众号