Python移動或復(fù)制文件夾并保持目錄結(jié)構(gòu)

IO錯誤未處理,使用代碼前請仔細看一下注釋,避免造成不可挽回的損失

# 拷貝文件夾并保持目錄結(jié)構(gòu)

import shutil
import os

source = '源文件夾'
target = '目標(biāo)文件夾'
count = 0  # 統(tǒng)計文件數(shù)量


def moveDir(src, dist):
    global count

    # 檢查目標(biāo)文件夾是否存在,不存在創(chuàng)建文件夾
    if (not os.path.exists(dist)):
        os.mkdir(dist)

    # 首先遍歷當(dāng)前目錄所有文件及文件夾
    filelist = os.listdir(src)
    # 準(zhǔn)備循環(huán)判斷每個元素是否是文件夾還是文件,是文件的話,把名稱傳入list,是文件夾的話,遞歸
    for file in filelist:
        # 獲取當(dāng)前文件或文件夾全路徑
        currentpath = os.path.join(src, file)
        # 判斷是否是文件夾
        if os.path.isdir(currentpath):
            # 繼續(xù)遍歷文件夾
            moveDir(os.path.join(src, file), os.path.join(dist, file))
        else:
            # 移動或復(fù)制文件
            count += 1
            (filepath, filename) = os.path.split(currentpath)
            # 拼接目標(biāo)文件路徑
            targetpath = os.path.join(dist, file)
            # 復(fù)制文件
            # shutil.copy(currentpath, targetpath)
            # 移動文件
            os.rename(currentpath, targetpath) # shutil.move(scurrentpath, targetpath)
            print(f'\r第{count}文件:{filename} 移動完成', end='')


if __name__ == '__main__':
    source = input('請輸入需要移動的文件夾:')
    target = input('請輸入需要移動到的位置:')

    # 開始移動
    print(f'開始移動文件夾!')
    moveDir(source, target)
    # 移動文件后留有空文件夾,需要主動刪除
    shutil.rmtree(source, ignore_errors=False, onerror=None)
    print('')
    print(f'文件夾移動完成:{source}->{target},共{count}個文件')

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容