python shutil模組學習筆記

2021-10-17 03:53:33 字數 2642 閱讀 5781

拷貝整個資料夾

刪除目錄

移動目錄或檔案

總結本文參考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.出現許可權錯誤,通過查詢資料,有提出斜槓方向不對和檔案不存在,經過重新看**,發現自己最初源路徑和目的路徑寫反了,因此不存在該檔案,修改後即可。

2.如果原始檔路徑為目錄,也會報錯(測試過)。

上述**直接將檔案複製到指定資料夾,使用 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路徑所指的檔案,需要注意的是如果檔案存在,可能會直接覆蓋

主要記錄了一些檔案複製、移動、刪除等一些比較常用的方法,除此之外,還有歸檔操作等,詳細操作可檢視官網,附官方文件中文官方文件

Python shutil模組用法

1.shutil.copyfile oldfile,newfile 複製檔案1到檔案2中,如txt檔案。注意 若檔案2不存在,則直接建立檔案2,且檔案2中內容和檔案1內容相同。若檔案2存在,則檔案2中原有內容會被清除掉。語法 shutil.copyfile oldfile,newfile impor...

shutil模組 python shutil模組

shutil.copyfile src,dst 從源src複製到dst中去。當然前提是目標位址是具備可寫許可權。丟擲的異常資訊為ioexception.如果當前的dst已存在的話就會被覆蓋掉 shutil.move src,dst 移動檔案或重新命名 shutil.copymode src,dst ...

詳解Python shutil模組

import shutil 高階的檔案,資料夾,壓縮包的處理模組,也主要用於檔案的拷貝 shutil.copyfileobj fsrc,fdst length 將檔案的內容拷貝到另乙個檔案 可以指定length長度進行拷貝 import shutil shutil.copyfilewww.cppcn...