python shutil模組學習筆記
技術標籤:python
shutil模組學習筆記
前言
本文參考python官方文件,進行學習並整理,附官方文件中文官方文件
一、總述
shutil模組提供了一系列對檔案和檔案集合的高階操作,對於單個檔案的操作,一般使用os
模組
二、檔案和目錄操作
拷貝單個檔案
shutil.copy(src, dst, *, follow_symlinks=True)
將檔案 src 拷貝到檔案或目錄 dst。 src 和 dst 應為路徑類物件 或字串。 如果 dst 指定了一個目錄,檔案將使用 src 中的基準檔名拷貝到 dst 中。 將返回新建立檔案所對應的路徑。
程式碼如下(示例):
import shutil
src_path = r"C:\Users\samsung\Desktop\test_shutil\copy.docx"
dst_path = r"C:\Users\samsung\Desktop"
a = shutil.copy(src_path,dst_path)
print(a)
輸出為
C:\Users\samsung\Desktop\copy.docx
即可將檔案src_path複製到dst_path所在的資料夾下,並返回新建立檔案所對應的路徑
執行過程中報錯
1.
出現許可權錯誤,通過查詢資料,有提出斜槓方向不對和檔案不存在,經過重新看程式碼,發現自己最初源路徑和目的路徑寫反了,因此不存在該檔案,修改後即可。
複製後可指定檔名
上述程式碼直接將檔案複製到指定資料夾,使用 src 中的檔名,也可改變複製檔案的檔名
程式碼如下(示例):
import shutil
src_path = r"C:\Users\samsung\Desktop\test_shutil\copy.docx"
dst_path = r"C:\Users\samsung\Desktop\copy1.docx"
a = shutil.copy(src_path,dst_path)
print(a)
拷貝整個資料夾
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)
將以 src 為根起點的整個目錄樹拷貝到名為 dst 的目錄並返回目標目錄。 dirs_exist_ok 指明是否要在 dst 或任何丟失的父目錄已存在的情況下引發異常。
import shutil
src_path = r"C:\Users\samsung\Desktop\test_shutil"
dst_path = r"C:\Users\samsung\Desktop\test_1"
a = shutil.copytree(src_path,dst_path)
print(a)
可將test_shutil中的所有內容複製到dst_path所在資料夾中,注意:test_1為不存在的資料夾
執行過程中報錯
1.dst_path中的路徑為已經存在的資料夾,則報錯,即不可以將一個資料夾直接複製到另外一個資料夾中,必須給資料夾重新命名
FileExistsError: [WinError 183] 當檔案已存在時,無法建立該檔案。: 'C:\\Users\\samsung\\Desktop'
刪除目錄
shutil.rmtree(path, ignore_errors=False, onerror=None)
刪除一個完整的目錄樹;path 必須指向一個目錄。
返回值為None,只要目錄存在,應該不會報錯
移動目錄或檔案
shutil.move(src, dst, copy_function=copy2)
遞迴地將一個檔案或目錄 (src) 移至另一位置 (dst) 並返回目標位置。
import shutil
src_path = r"C:\Users\samsung\Desktop\copy.docx"
dst_path = r"C:\Users\samsung\Desktop\test_shutil\copu.docx"
#
# a = shutil.copytree(src_path,dst_path)
a = shutil.move(src_path,dst_path)
print(a)
注意事項
1.可以將檔案直接移動到資料夾中,即src為檔案,dst為資料夾,將src指向的檔案移動到dst資料夾下
2.src和dst均為資料夾,將整個src資料夾移動到dst下
3.src為檔案,dst為檔案時,即可將src的檔案複製為dst路徑所指的檔案,需要注意的是如果檔案存在,可能會直接覆蓋
總結
主要記錄了一些檔案複製、移動、刪除等一些比較常用的方法,除此之外,還有歸檔操作等,詳細操作可檢視官網,附官方文件中文官方文件