Python文件夾常用操作

LueOsburn 8年前發布 | 5K 次閱讀 Python

[Python]代碼    

#_*_encoding:utf-8_*_

#-------------------------------------------------------------------------------

# Name:        文件夾常用操作

# Purpose:

#

# Author:      QiuChangJie

#

# Created:     07/06/2015

# Copyright:   (c) cj.qiu 2015

# Licence:     <your licence>

#-------------------------------------------------------------------------------

import sys
import os
import shutil
import platform


class FileUtils:
    @staticmethod
    def fileFilterExt(args, dirn, fln):
        for fls in fln:
            if fls.lower().endswith(args[1].lower()) and os.path.isfile(os.path.join(dirn, fls)):
                args[0].append(os.path.join(dirn,fls))

    @staticmethod
    def dirFilterExt(args, dirn, fln):
        for fls in fln:
            if fls.lower().endswith(args[1].lower()) and os.path.isdir(os.path.join(dirn, fls)):
                args[0].append(os.path.join(dirn,fls))

    # 根據文件擴展名獲取文件
    @staticmethod
    def getFiles(root, ext):
        fileList = list()
        os.path.walk(root, FileUtils.fileFilterExt, (fileList, ext))
        return fileList

    # 獲取文件夾
    @staticmethod
    def getDirs(root, ext):
        dirList = list()
        os.path.walk(root, FileUtils.dirFilterExt, (dirList, ext))
        return dirList

    # 復制文件到指定目錄
    @staticmethod
    def copyFileExt(src, dst):
        if not os.path.exists(src):
            print(str.format("%s is not exists", src))
            return

        dirList = FileUtils.getDirs(src, "")
        for d in dirList:
            subDir = d[len(src) + 1:]
            if not os.path.exists(os.path.join(dst, subDir)):
                os.mkdir(os.path.join(dst, subDir))

        fileList = FileUtils.getFiles(src, "")
        for f in fileList:
            subName = f[len(src) + 1:]
            shutil.copy(f, os.path.join(dst, subName))
 本文由用戶 LueOsburn 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!