python腳本編程:批量複製或刪除文件

# -*- coding: utf-8 -*-
__author__ = 'hujianli'
import os
import shutil
yuanD = "F:\scripts\monitor"
mubiaoD = "F:\scripts\CheungSSH\web"
#遞歸複製文件夾內的文件
def copyFiles(sourceDir,targetDir):
    #忽略某些特定的子文件夾
    if sourceDir.find("exceptionfolder")>0:
        return

    #列出源目錄文件和文件夾
    for file in os.listdir(sourceDir):
        #拼接完整路徑
        sourceFile = os.path.join(sourceDir,file)
        targetFile = os.path.join(targetDir,file)

        #如果是文件則處理
        if os.path.isfile(sourceFile):
            #如果目的路徑不存在該文件就創建空文件,並保持目錄層級結構
            if not os.path.exists(targetDir):
                os.makedirs(targetDir)
            #如果目的路徑裏面不存在某個文件或者存在那個同名文件但是文件有殘缺,則複製,否則跳過
            if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
                open(targetFile, "wb").write(open(sourceFile, "rb").read())
                print targetFile+" copy succeeded"

        #如果是文件夾則遞歸
        if os.path.isdir(sourceFile):
            copyFiles(sourceFile, targetFile)

#遍歷某個目錄及其子目錄下所有文件拷貝到某個目錄中
def copyFiles2(srcPath,dstPath):
    if not os.path.exists(srcPath):
        print "src path not exist!"
    if not os.path.exists(dstPath):
        os.makedirs(dstPath)
    #遞歸遍歷文件夾下的文件,用os.walk函數返回一個三元組
    for root,dirs,files in os.walk(srcPath):
        for eachfile in files:
            shutil.copy(os.path.join(root,eachfile),dstPath)
            print eachfile+" copy succeeded"


#刪除某目錄下特定文件
def removeFileInDir(sourceDir):
    for file in os.listdir(sourceDir):
        file=os.path.join(sourceDir,file) #必須拼接完整文件名
        if os.path.isfile(file) and file.find(".jpg")>0:
            os.remove(file)
            print file+" remove succeeded"

if  __name__ =="__main__":
    copyFiles(yuanD,mubiaoD)
    #removeFileInDir("./dir2")
    #copyFiles2("./dir1","./dir2")


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章