利用treelib库模拟文件管理系统

利用treelib库模拟文件管理系统

treelib官方文档

1.建立对象
  • Interface 界面类
  • MultiTree 多叉树类

interface.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Minions
# @Date: 2019-12-6 9:10:38
# @Last Modified by:  Minions
# @Last Modified time: 2019-12-7 10:32:58

class Interface(object):
    def __init__(self):
        pass

    def operationTips(self):
        tipsText = \
        """
        ************************************************
        *
        *
        *           欢迎进入Minions的文件管理系统
        *
        *
        *           改变目录:格式:cd <目录名>
        *           显示目录:格式:dir[<目录名>]
        *           创建目录:格式:md <目录名>
        *           删除目录:格式:rd<目录名>
        *           新建文件:格式:edit<文件名>
        *           删除文件:格式:del<文件名>
        *           退出文件系统:exit
        *
        *
        ************************************************
        """
        print(tipsText)

2.明确目标

main.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Minions
# @Date: 2019-12-6 9:07:35
# @Last Modified by:  Minions
# @Last Modified time: 2019-12-8 10:29:56

from interface import Interface
from multiTree import MultiTree
import os


def main():
    # 创建界面对象
    face = Interface()

    # 创建多叉树对象
    multiTree = MultiTree()

    face.operationTips()
    while True:
        try:
            operation, path = input("%s>>>" % multiTree.curRePath).split()
            if operation == "cd":
                multiTree.changeDir(path)
            elif operation == "dir":
                multiTree.dir(path)
            elif operation == "md":
                multiTree.makeDir(path)
            elif operation == "rd":
                multiTree.removeDir(path)
            elif operation == "edit":
                multiTree.editFile(path)
            elif operation == "del":
                multiTree.delFile(path)
            elif operation == "help" and path == '~':
                face.operationTips()
            elif operation == "show" and path=="all":
                multiTree.tree.show()
            elif operation == "exit":
                os._exit(0)
        except:
            print("需要传递两个参数")

if __name__ == '__main__':
    main()
3.具体实施

multiTree.py


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Minions
# @Date: 2019-12-6 9:29:56
# @Last Modified by:  Minions
# @Last Modified time: 2019-12-8 16:10:25

from treelib import Tree

# 创建一个多叉树的类
class MultiTree(object):
    def __init__(self):
        self.tree = Tree()
        self.curRePath = "root"     # 当前路径
        self.curRefNode = self.tree.create_node("Root", "root") # 当前节点
        # 初始化创建
        self.tree.create_node("User","user","root")
        self.tree.create_node("1","1","user")
        self.tree.create_node("2","2","user")
        self.tree.create_node("1.txt","f-1.txt", "root")

    # 分割目录
    def splitDir(self, path):
        listCurDir = self.curRePath.split('/')
        listDir = path.split('/')
        # 如果目录为一级,直接判断当前节点是否是该节点的父亲,如果是root则无需判断
        if len(listDir) == 1:
            if not self.tree.contains(listDir[0]):
                return False
            if listDir[0] == "root":
                return [True, "root", self.tree.get_node("root")]
            if self.tree.parent(listDir[0]) == self.curRefNode:
                curRefNode = self.tree.get_node(listDir[-1])
                curRePath = self.curRePath+'/'+curRefNode.identifier
                return [True, curRePath, curRefNode ]
            else:
                return False

        # 如果目录为多级
        for i in range(1,len(listDir)):
            # 相对路径 如果第一个节点不为root,那当前节点是第一个节点的父亲且前面节点为后面节点的父亲
            if listDir[0] != "root":
                try:    # 如果不存在listDir[i]
                    if self.tree.parent(listDir[i]).identifier == listDir[i-1] \
                            and self.tree.parent(listDir[0]) == self.curRefNode:
                       pass
                    else:
                        return False
                except:
                    return False
            # 绝对路径
            else:
                listCurDir = []
                try:  # 如果不存在listDir[i]
                    if self.tree.parent(listDir[i]).identifier == listDir[i - 1]:
                        pass
                    else:
                        return False
                except:
                    return False

        # 合并俩个列表并且去重
        listCurDir.extend(listDir)
        newDir = sorted(set(listCurDir),key=listCurDir.index)
        # 赋值给新建的节点和路径, 具体赋值传递给具体函数
        curRePath = "/".join(newDir)
        curRefNode = self.tree.get_node(listDir[-1])
        return [True, curRePath, curRefNode]

    # 分割文件
    def splitFile(self, name):
        # 创建文件必须带后缀名
        if len(name.split('.')) == 1:
            return False
        elif len(name.split('.')) == 2:
            # user/1/ 1.txt
            if len(name.split('/')) == 1:
                return [True, self.curRePath, self.curRefNode]

            else:
                result = self.splitDir("".join(name.split('/')[:-1]))
                if not result:
                    return False
                if result[0]:
                    curRePath = result[1]
                    curRefNode = result[2]
                    return [True, curRePath, curRefNode]
        else:
            return False

    # 改变目录
    def changeDir(self, toPath):
        if toPath == "..":
            if self.curRefNode.identifier == "root":
                return True
            else:
                self.curRefNode = self.tree.parent(self.curRefNode.identifier)
                self.curRePath = "/".join(self.curRePath.split('/')[:-1])
                return True
        if len(toPath.split('.')) != 1:
            print("系统找不到指定的路径。")
            return False
        result = self.splitDir(toPath)
        if not result:
            print("系统找不到指定的路径。")
            return False
        if result[0]:
            self.curRePath = result[1]
            self.curRefNode = result[2]

    # 显示目录
    def dir(self, path):
        # self.tree.show()
        if path == "cur":
            children = self.tree.children(self.curRefNode.identifier)
        else:
            result = self.splitDir(path)
            if not result:
                print("系统找不到指定的路径。")
                return False
            if result[0]:
                curRefNode = result[2]
            children = self.tree.children(curRefNode.identifier)
        if len(children) == 0:
            print("该文件夹下无文件。")
        for child in children:
            if child.identifier[0:2] == 'f-':
                print('\t<FILE>\t\t\t',child.identifier[2:])
            else:
                print('\t<DIR>\t\t\t',child.identifier)

    # 创建目录  注: identifier唯一,父子名称相同不行
    def makeDir(self, name):
        try:
            if '.' in name or '/' in name or '-' in name:
                print("存在特殊字符,无法创建")
                return False
            self.tree.create_node(name.title, name, self.curRefNode.identifier)
        except:
            print("创建目录失败。")

    # 删除目录
    def removeDir(self, name):
        result = self.splitDir(name)
        if not result:
            print("系统找不到指定的路径。")
            return False
        if result[0]:
            curRefNode = result[2]
            self.tree.remove_node(curRefNode.identifier)
        else:
            print("系统找不到指定的文件。")

    # 创建文件时给他添加'f-'区分
    def editFile(self, name):
        result = self.splitFile(name)
        if name.count('.') > 1:     # 创建文件只能有一个.
            print("文件名有误。")
            return False
        fileName = name.split('/')[-1]
        if not result:
            print("系统找不到指定的文件。")
            return False
        if result[0]:
            if result[2].identifier[0:2] == 'f-':
                print("文件下不能创建文件")
            try:
                self.tree.create_node(fileName.title, 'f-' + fileName,
                                      result[2].identifier)
            except:
                print("创建文件失败。")

    # 删除文件
    def delFile(self, name):
        result = self.splitFile(name)
        fileName = name.split('/')[-1]
        if not result:
            print("系统找不到指定的文件。")
            return False
        if result[0]:
            if self.tree.parent('f-'+fileName) == result[2]:
                self.tree.remove_node('f-'+fileName)
            else:
                print("没有该文件")
4.运行截图

在这里插入图片描述
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页