1. 程式人生 > >《可愛的Python》讀書筆記(六)

《可愛的Python》讀書筆記(六)

mkdir

沒有完美的軟件,夠用並且容易使用的軟件已經算是完美的了。


今天整理這幾天的代碼

# -*- coding: utf-8 -*-
import os
import sys
import cmd
from cdctools import *


class PyCDC(cmd.Cmd):


    def __init__(self):
    
        # 初始化基類
        cmd.Cmd.__init__(self)
        self.CDROM = 'E:\\iso\\CentOS-6.8-x86_64-bin-DVD1'
        self.CDDIR = 'F:\\back\\'
        # 定義命令行環境的前綴字符
        self.prompt = "(PyCDC)>"
        # 定義命令行環境的最初提示
        self.intro = """使用說明:
        dir 目錄名   # 指定保存和搜索目錄,默認是"F:\\back\\"
        walk 文件名  # 指定光盤信息文件名,使用"*.cdc"
        find 關鍵詞  # 使用在保存和搜索目錄中遍歷所有.cdc文件,輸出含有關鍵詞的行
        ?     #查詢
        quit  #推出系統,也可以使用Ctrl+D(Unix)|Ctrl+Z(Dos/windows)
        """
        
    def do_walk(self, filename):  
        if filename == "":
            filename = input("請輸入cdc文件名:")
        print("指定保存的文件名為:'%s'" % filename)
        cdWalker(self.CDROM, self.CDDIR+filename)
        
    def help_walk(self):  
        print("掃描指定路徑的目錄結構,並輸出到指定的'.cdc'文件中")
        
    def do_dir(self, pathname):
        if pathname == "":
            pathname = input("請輸入指定保存/搜索目錄(默認是:'%s'):" % (self.CDDIR))
        self.CDDIR = pathname
        print("指定保存/搜索目錄為:'%s'" % (pathname))
        mkdir(pathname)
        
    def help_dir(self):
        print("指定保存/搜索目錄")
        
    def do_find(self, keyword):
        if keyword == "":
            keyword = input("請輸入搜索關鍵詞:")
        print("指定搜索關鍵詞為:'%s'" % keyword)
        cdcGrep(self.CDDIR, keyword)
        
    def help_find(self):
        print("搜索關鍵詞")
      
    def do_quit(self, arg):
        sys.exit()
        
    def help_quit(self):
        print("退出程序")
        
    # 定義quit的快捷方式
    do_q = do_quit
    
    
def cdWalker(cdrom, cdcfile):
    '''
    掃描指定路徑的目錄結構並保存為新的文件
    '''
    export = []
    for root, dirs, files in os.walk(cdrom):
        export.append("\n %s;%s;%s" % (root, dirs, files))
    open(cdcfile, 'w').write(''.join(export))
    print('掃描目錄結構保存到{}'.format(cdcfile))
    
def cdcGrep(cdcpath, keyword):
    '''
    光盤信息文本關鍵詞搜索
    '''
    # 搜索目錄中的文件
    filelist = os.listdir(cdcpath)
    cdcpath = cdcpath + "\\"
    # 循環文件列表
    for cdc in filelist:                   
        if os.path.isdir(cdcpath+cdc):
            print('搜索子目錄{}'.format(cdcpath+cdc))
            # 若是子目錄,則遞歸調用完成查找
            cdcGrep(cdcpath+cdc, keyword)
        else:
            if cdc.endswith('.cdc'):
                print('找到目標文件:{}'.format(cdc))
                # 拼合文件路徑,並打開文件
                cdcfile = open(cdcpath + cdc)
                # 讀取文件每一行,並循壞
                for line in cdcfile.readlines():
                    # 判斷是否有關鍵詞在行中
                    if keyword in line:
                        print(line)
                        
def mkdir(pathname):
    '''
    自動創建不存在的目錄
    '''
    # 去除首尾空格
    path=pathname.strip()
     # 去除尾部 \ 符號
    path=pathname.rstrip("\\")
    # 判斷路徑是否存在
    if not os.path.exists(pathname):
        try:
            # 創建目錄
            os.makedirs(pathname)
            print('指定的目錄不存在,將自動為您創建')
        except FileNotFoundError as reason:
            print(reason)
            
            
if __name__ == '__main__':
    cdc = PyCDC()
    cdc.cmdloop()

運行效果如下:

使用說明:
        dir 目錄名   # 指定保存和搜索目錄,默認是"F:\back\"
        walk 文件名  # 指定光盤信息文件名,使用"*.cdc"
        find 關鍵詞  # 使用在保存和搜索目錄中遍歷所有.cdc文件,輸出含有關鍵詞的行
        ?     #查詢
        quit  #推出系統,也可以使用Ctrl+D(Unix)|Ctrl+Z(Dos/windows)
        
(PyCDC)>walk
請輸入cdc文件名:1.cdc
指定保存的文件名為:'1.cdc'
掃描目錄結構保存到F:\back\1.cdc
(PyCDC)>?dir
指定保存/搜索目錄
(PyCDC)>dir
請輸入指定保存/搜索目錄(默認是:'F:\back\'):G:\back指定保存/搜索目錄為:'G:\back\'
[WinError 3] 系統找不到指定的路徑。: 'G:\\'
(PyCDC)>dir F:\back\bak指定保存/搜索目錄為:'F:\back\bak\'
指定的目錄不存在,將自動為您創建
(PyCDC)>walk 2.cdc
指定保存的文件名為:'2.cdc'
掃描目錄結構保存到F:\back\bak\2.cdc
(PyCDC)>find
請輸入搜索關鍵詞:image
指定搜索關鍵詞為:'image'
找到目標文件:2.cdc
 E:\iso\CentOS-6.8-x86_64-bin-DVD1;['EFI', 'images', 'isolinux', '[BOOT]'];['.discinfo', '.treeinfo', 'CentOS_BuildTag', 'EULA', 'GPL', 'RELEASE-NOTES-en-US.html', 'RPM-GPG-KEY-CentOS-6', 'RPM-GPG-KEY-CentOS-Debug-6', 'RPM-GPG-KEY-CentOS-Security-6', 'RPM-GPG-KEY-CentOS-Testing-6', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images;['pxeboot'];['efiboot.img', 'efidisk.img', 'install.img', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\pxeboot;[];['initrd.img', 'TRANS.TBL', 'vmlinuz']
(PyCDC)>dir F:\back
指定保存/搜索目錄為:'F:\back'
(PyCDC)>find images
指定搜索關鍵詞為:'images'
找到目標文件:1.cdc
 E:\iso\CentOS-6.8-x86_64-bin-DVD1;['EFI', 'images', 'isolinux', '[BOOT]'];['.discinfo', '.treeinfo', 'CentOS_BuildTag', 'EULA', 'GPL', 'RELEASE-NOTES-en-US.html', 'RPM-GPG-KEY-CentOS-6', 'RPM-GPG-KEY-CentOS-Debug-6', 'RPM-GPG-KEY-CentOS-Security-6', 'RPM-GPG-KEY-CentOS-Testing-6', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images;['pxeboot'];['efiboot.img', 'efidisk.img', 'install.img', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\pxeboot;[];['initrd.img', 'TRANS.TBL', 'vmlinuz']
搜索子目錄F:\back\back1
搜索子目錄F:\back\back1\back11
搜索子目錄F:\back\back2
搜索子目錄F:\back\bak
找到目標文件:2.cdc
 E:\iso\CentOS-6.8-x86_64-bin-DVD1;['EFI', 'images', 'isolinux', '[BOOT]'];['.discinfo', '.treeinfo', 'CentOS_BuildTag', 'EULA', 'GPL', 'RELEASE-NOTES-en-US.html', 'RPM-GPG-KEY-CentOS-6', 'RPM-GPG-KEY-CentOS-Debug-6', 'RPM-GPG-KEY-CentOS-Security-6', 'RPM-GPG-KEY-CentOS-Testing-6', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images;['pxeboot'];['efiboot.img', 'efidisk.img', 'install.img', 'TRANS.TBL']
 E:\iso\CentOS-6.8-x86_64-bin-DVD1\images\pxeboot;[];['initrd.img', 'TRANS.TBL', 'vmlinuz']
(PyCDC)>q


以上代碼加入了“在手動指定了不存在的保存/搜索目錄時將自動創建改目錄”的功能,實現了完成版本的PyCDC!

《可愛的Python》讀書筆記(六)