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}個文件')