Python標準庫中的
shutil
模組提供了一組用於對檔和目錄進行操作的函式。
它可以幫助我們執行諸如復制、移動、重新命名以及刪除檔和目錄等操作,比
os.path
功能更強大。
下面透過一個簡單的套用案例來展示其用法。
假設我們有一個資料夾
source_folder
,裏面有一些檔和子資料夾,我們想要將其中的內容復制到另一個資料夾
destination_folder
中,我們可以使用
shutil.copytree()
函式來實作:
import shutil
# 將源資料夾內容復制到目的檔夾
shutil.copytree('source_folder', 'destination_folder')
主要函式和方法
shutil.copy(src, dst)
: 復制檔從源路徑 src 到目標路徑 dst。
shutil.move(src, dst)
: 移動檔或重新命名檔從源路徑 src 到目標路徑 dst。
shutil.copytree(src, dst)
: 遞迴地復制整個目錄樹從源目錄 src 到目標目錄 dst。
shutil.rmtree(path)
: 遞迴地刪除目錄以及目錄中的所有內容。
shutil.make_archive(base_name, format, root_dir)
: 建立一個歸檔檔。
shutil.unpack_archive(filename, extract_dir)
: 解壓縮歸檔檔到指定的目錄。
shutil.disk_usage(path)
: 返回給定路徑的磁盤使用情況,以字節為單位。
shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)
: 在 PATH 中尋找給定命令的位置。
核心套用場景
「檔備份:」 在日常工作中,我們經常需要備份重要檔。使用
shutil.copy()
可以輕松建立檔的備份。shutil.copy('important_file.txt', 'backup_folder/important_file_backup.txt')
「計畫歸檔:」 當我們需要將一個計畫打包成一個歸檔檔以便於分享或存檔時,可以使用
shutil.make_archive()
函式。shutil.make_archive('project_archive', 'zip', root_dir='project_folder')
「安全刪除:」 有時候我們需要徹底刪除一個目錄及其內容,包括子目錄和檔。
shutil.rmtree()
函式可以幫助我們完成這個任務。shutil.rmtree('directory_to_delete')
總結
shutil
庫提供了一組方便易用的函式和方法,用於處理檔和目錄操作,如復制、移動、重新命名和刪除等。
無論是在日常檔操作、計畫管理還是數據清理等場景下,
shutil
庫都能發揮重要作用。
加入知識星球【我們談論數據科學】
600+小夥伴一起學習!