1. 程式人生 > >[轉]Python shutil 模塊

[轉]Python shutil 模塊

相關 篩選 recent 文件名 ring 地址 -c 都對 多文件

轉自:

https://www.cnblogs.com/wuzhiblog/p/6535527.html

https://www.cnblogs.com/caibao666/p/6433864.html


shutil 復制、移動、重命名、刪除

shutil 名字來源於 shell utilities,有學習或了解過Linux的人應該都對 shell 不陌生,可以借此來記憶模塊的名稱。該模塊擁有許多文件(夾)操作的功能,包括復制、移動、重命名、刪除等等

  1. 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‘

    如代碼所示,該函數的返回值是復制成功後的字符串格式的文件路徑

  2. 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‘

如以上代碼所示,該函數的返回值是復制成功後的文件夾的絕對路徑字符串
所以該函數可以當成是一個備份功能
  1. 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‘

  1. 永久性刪除文件和文件夾
    這裏有涉及到 os 模塊中的相關函數
    os.unlink(path) 會刪除 path 路徑文件
    os.rmdir(path) 會刪除 path 路徑文件夾,但是這個文件夾必須是空的,不包含任何文件或子文件夾
    shutil.rmtree(path) 會刪除 path 路徑文件夾,並且在這個文件夾裏面的所有文件和子文件夾都會被刪除

利用函數執行刪除操作時,應該倍加謹慎,因為如果想要刪除 txt 文件,而不小心寫到了 rxt ,那麽將會給自己帶來麻煩
此時,我們可以利用字符串的 endswith 屬性對文件格式進行檢查與篩選


shutil:高級的 文件、文件夾、壓縮包 處理模塊

shutil.copyfileobj(fsrc, fdst[, length])(copyfileobj方法只會拷貝文件內容)
將文件內容拷貝到另一個文件中

import shutil

shutil.copyfileobj(open(‘old.xml‘,‘r‘), open(‘new.xml‘, ‘w‘))

shutil.copyfile(src, dst)  (copyfile只拷貝文件內容)
拷貝文件

shutil.copyfile(‘f1.log‘, ‘f2.log‘)

shutil.copy(src, dst) 拷貝文件和權限

shutil.copy(‘f1.log‘, ‘f2.log‘)

shutil.copy2(src, dst)

拷貝文件和狀態信息

shutil.copy2(‘f1.log‘, ‘f2.log‘

shutil.copymode(src, dst)  (前提是dst文件存在,不然報錯)
僅拷貝權限。內容、組、用戶均不變

shutil.copymode(‘f1.log‘, ‘f2.log‘)

shutil.copystat(src, dst)
僅拷貝狀態的信息,即文件屬性,包括:mode bits, atime, mtime, flags

shutil.copystat(‘f1.log‘, ‘f2.log‘)

shutil.ignore_patterns(*patterns)  (忽略哪個文件,有選擇性的拷貝)

shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾

shutil.copytree(‘folder1‘, ‘folder2‘, ignore=shutil.ignore_patterns(‘*.pyc‘, ‘tmp*‘))
shutil.copytree(‘f1‘, ‘f2‘, symlinks=True, ignore=shutil.ignore_patterns(‘*.pyc‘, ‘tmp*‘))

shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件

shutil.rmtree(‘folder1‘)

shutil.move(src, dst)
遞歸的去移動文件,它類似mv命令,其實就是重命名。

shutil.move(‘folder1‘, ‘folder3‘)

shutil.make_archive(base_name, format,...)

創建壓縮包並返回文件路徑,例如:zip、tar

創建壓縮包並返回文件路徑,例如:zip、tar

  • base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑, 如:www =>保存至當前路徑 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要壓縮的文件夾路徑(默認當前目錄)
  • owner: 用戶,默認當前用戶
  • group: 組,默認當前組
  • logger: 用於記錄日誌,通常是logging.Logger對象 技術分享圖片
    #將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄
    
    import shutil
    
    ret = shutil.make_archive("wwwwwwwwww", ‘gztar‘, root_dir=‘/Users/wupeiqi/Downloads/test‘)
    
     
    #將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄
    
    import shutil
    
    ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", ‘gztar‘, root_dir=‘/Users/wupeiqi/Downloads/test‘)
    技術分享圖片


shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的,詳細:

技術分享圖片
import zipfile

# 壓縮
z = zipfile.ZipFile(‘laxi.zip‘, ‘w‘)
z.write(‘a.log‘)
z.write(‘data.data‘)
z.close()

# 解壓
z = zipfile.ZipFile(‘laxi.zip‘, ‘r‘)
z.extractall()
z.close()
技術分享圖片 技術分享圖片
import tarfile

# 壓縮
tar = tarfile.open(‘your.tar‘,‘w‘)
tar.add(‘/Users/wupeiqi/PycharmProjects/bbs2.log‘, arcname=‘bbs2.log‘)
tar.add(‘/Users/wupeiqi/PycharmProjects/cmdb.log‘, arcname=‘cmdb.log‘)
tar.close()

# 解壓
tar = tarfile.open(‘your.tar‘,‘r‘)
tar.extractall()  # 可設置解壓地址
tar.close()
技術分享圖片


備註:zipfile壓縮不會保留文件的狀態信息,而tarfile會保留文件的狀態信息

[轉]Python shutil 模塊