Python学习笔记_文件读写,目录遍历类封装

文件读写和目录遍历类的封装.

  • mylib.py
 1 # -*- coding:utf-8 -*-
 2 
 3 __author__ = 'huanghuan'
 4 
 5 import os
 6 from os.path import basename, isdir
 7 from os import listdir
 8 
 9 # 文件读写类: 2个功能
10 class MyFile(object):
11     """docstring for MyFile"""
12     def __init__(self):
13         super(MyFile, self).__init__()
14 
15     def read(self, name):   # read file
16         self.buf = []
17         f = open(name, 'r')
18         for line in f.readlines():
19             self.buf.append(line.strip())
20         f.close()
21 
22     def write(self, name, buf):   # write file
23         f = open(name, 'w')
24         for line in buf:
25             f.write(line)
26         f.close()
27 
28 # 目录遍历类: 1个功能
29 class MyPath(object):
30     """docstring for MyPath"""
31     def __init__(self):
32         super(MyPath, self).__init__()
33         self.dir = []
34         
35     def get(self, dir):   # get dir, load in buf.
36         self.buf = []
37         for item in os.walk(dir):
38             for i in item[2]:
39                 s_path = '%s\\%s' % (item[0], i)
40                 self.buf.append(s_path)
41 
42     def traverse(self, path, depth=0): # abandoned function.
43         line = '%s|%s' % ('|\t' * depth, basename(path))
44         print line
45         self.dir.append(line)
46 
47         if isdir(path):
48             for item in listdir(path):
49                 my_traverse_path(path + '/' + item, depth + 1)
50 
51 
52 
53 if __name__ == '__main__':
54     p = MyPath()
55     p.get(os.getcwd())
56     for line in p.buf:
57         print line

 

对常用的文件读写和目录遍历操作,进行简单的封装,方便调用.

posted on 2015-01-04 14:18  selfrebuild  阅读(287)  评论(0)    收藏  举报

导航