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)) 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/8110.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论