溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python glob與shutil庫結(jié)合實(shí)現(xiàn)文件的批量復(fù)制與移動

發(fā)布時(shí)間:2024-07-25 16:46:04 來源:億速云 閱讀:82 作者:小樊 欄目:編程語言
import glob
import shutil

# 指定要復(fù)制或移動的文件的路徑
source_dir = 'path/to/source/directory/'
dest_dir = 'path/to/destination/directory/'

# 使用glob庫獲取source_dir中所有的文件路徑
file_paths = glob.glob(source_dir + '*')

# 遍歷所有文件路徑,逐一復(fù)制或移動到dest_dir
for file_path in file_paths:
    file_name = file_path.split('/')[-1]  # 獲取文件名
    dest_path = dest_dir + file_name
    
    # 復(fù)制文件
    shutil.copy(file_path, dest_path)
    
    # 移動文件
    # shutil.move(file_path, dest_path)
    
    print(f'Copied {file_path} to {dest_path}')
    # print(f'Moved {file_path} to {dest_path}')

在上面的代碼中,首先使用glob庫獲取source_dir中所有的文件路徑,然后遍歷所有文件路徑,逐一復(fù)制或移動到dest_dir中。通過調(diào)用shutil庫中的copy()方法可以實(shí)現(xiàn)文件的復(fù)制,調(diào)用move()方法可以實(shí)現(xiàn)文件的移動。根據(jù)需要選擇使用copy()方法或move()方法。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI