學於https://automatetheboringstuff.com
shutil 名字來源於 shell utilities,有學習或了解過Linux的人應該都對 shell 不陌生,可以借此來記憶模塊的名稱。該模塊擁有許多文件(夾)操作的功能,包括復制、移動、重命名、刪除等等
-
chutil.copy(source, destination)
shutil.copy() 函數實現文件復制功能,將 source 文件復制到 destination 文件夾中,兩個參數都是字符串格式。如果 destination 是一個文件名稱,那么它會被用來當作復制后的文件名稱,即等於 復制 + 重命名。舉例如下:>> import shutil
>> import os
>> os.chdir('C:\')
>> shutil.copy('C:\spam.txt', 'C:\delicious')
'C:\delicious\spam.txt'
>> shutil.copy('eggs.txt', 'C:\delicious\eggs2.txt')
'C:\delicious\eggs2.txt'如代碼所示,該函數的返回值是復制成功后的字符串格式的文件路徑
-
shutil.copytree(source, destination)
shutil.copytree()函數復制整個文件夾,將 source 文件夾中的所有內容復制到 destination 中,包括 source 里面的文件、子文件夾都會被復制過去。兩個參數都是字符串格式。注意,如果 destination 文件夾已經存在,該操作並返回一個 FileExistsError 錯誤,提示文件已存在。即表示,如果執行了該函數,程序會自動創建一個新文件夾(destination參數)並將 source 文件夾中的內容復制過去
舉例如下:
>> import shutil
>> import os
>> os.chdir('C:\')
>> shutil.copytree('C:\bacon', 'C:\bacon_backup')
'C:\bacon_backup'
如以上代碼所示,該函數的返回值是復制成功后的文件夾的絕對路徑字符串
所以該函數可以當成是一個備份功能
- shutil.move(source, destination)
shutil.move() 函數會將 source 文件或文件夾移動到 destination 中。返回值是移動后文件的絕對路徑字符串。
如果 destination 指向一個文件夾,那么 source 文件將被移動到 destination 中,並且保持其原有名字。例如:
>> import shutil
>> shutil.move('C:\bacon.txt', 'C:\eggs')
'C:\eggs\bacon.txt'
上例中,如果 C:\eggs 文件夾中已經存在了同名文件 bacon.txt,那么該文件將被來自於 source 中的同名文件所重寫。
如果 destination 指向一個文件,那么 source 文件將被移動並重命名,如下:
>> shutil.move('C:\bacon.txt', 'C:\eggs\new_bacon.txt')
'C:\eggs\new_bacon.txt'
等於是移動+重命名
<b>注意,如果 destination 是一個文件夾,即沒有帶后綴的路徑名,那么 source 將被移動並重命名為 destination</b>,如下:
>> shutil.move('C:\bacon.txt', 'C:\eggs')
'C:\eggs'
即 bacon.txt 文件已經被重命名為 eggs,是一個沒有文件后綴的文件
最后,destination 文件夾必須是已經存在的,否則會引發異常:
>> shutil.move('spam.txt', 'C:\does_not_exist\eggs\ham')
Traceback (most recent call last):
File "D:\Python36\lib\shutil.py", line 538, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 3] 系統找不到指定的路徑。: 'test.txt' -> 'C:\does_not_exist\eggs\ham'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in
shutil.move('test.txt', 'C:\does_not_exist\eggs\ham')
File "D:\Python36\lib\shutil.py", line 552, in move
copy_function(src, real_dst)
File "D:\Python36\lib\shutil.py", line 251, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "D:\Python36\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\does_not_exist\eggs\ham'
- 永久性刪除文件和文件夾
這里有涉及到 os 模塊中的相關函數
os.unlink(path) 會刪除 path 路徑文件
os.rmdir(path) 會刪除 path 路徑文件夾,但是這個文件夾必須是空的,不包含任何文件或子文件夾
shutil.rmtree(path) 會刪除 path 路徑文件夾,並且在這個文件夾里面的所有文件和子文件夾都會被刪除
利用函數執行刪除操作時,應該倍加謹慎,因為如果想要刪除 txt 文件,而不小心寫到了 rxt ,那么將會給自己帶來麻煩
此時,我們可以利用字符串的 endswith 屬性對文件格式進行檢查與篩選
