IO錯(cuò)誤未處理唬血,使用代碼前請(qǐng)仔細(xì)看一下注釋仰禽,避免造成不可挽回的損失
# 拷貝文件夾并保持目錄結(jié)構(gòu)
import shutil
import os
source = '源文件夾'
target = '目標(biāo)文件夾'
count = 0 # 統(tǒng)計(jì)文件數(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)判斷每個(gè)元素是否是文件夾還是文件鞋屈,是文件的話,把名稱傳入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:
# 移動(dòng)或復(fù)制文件
count += 1
(filepath, filename) = os.path.split(currentpath)
# 拼接目標(biāo)文件路徑
targetpath = os.path.join(dist, file)
# 復(fù)制文件
# shutil.copy(currentpath, targetpath)
# 移動(dòng)文件
os.rename(currentpath, targetpath) # shutil.move(scurrentpath, targetpath)
print(f'\r第{count}文件:{filename} 移動(dòng)完成', end='')
if __name__ == '__main__':
source = input('請(qǐng)輸入需要移動(dòng)的文件夾:')
target = input('請(qǐng)輸入需要移動(dòng)到的位置:')
# 開(kāi)始移動(dòng)
print(f'開(kāi)始移動(dòng)文件夾酝惧!')
moveDir(source, target)
# 移動(dòng)文件后留有空文件夾,需要主動(dòng)刪除
shutil.rmtree(source, ignore_errors=False, onerror=None)
print('')
print(f'文件夾移動(dòng)完成:{source}->{target},共{count}個(gè)文件')