python中shutil和shutil庫的用法

一、shutil目錄和文件操作

Python shutil庫提供了對文件和目錄複製、移動、刪除、壓縮、解壓等操作。

1. 複製文件或目錄

  • shutil.copy(src, dst):複製文件或目錄
  • shutil.copyfile(src, dst):複製文件,src和dst只能是文件
  • shutil.copytree(src, dst, dirs_exist_ok=False):複製目錄,默認dst目錄不存在,否則會報錯。

示例:

import os
import shutil

dirpath    = os.path.dirname(os.path.realpath(__file__))
sourcedir  = os.path.join(dirpath, "shutil_a")
sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        
destdir    = os.path.join(dirpath, "shutil_b")
destfile   = os.path.join(dirpath, "shutil_b", "test2.txt")
# 複製文件或目錄
shutil.copy(sourcefile, destdir)        
# 複製文件
shutil.copyfile(sourcefile, destfile) 
# 複製目錄
shutil.copytree(sourcedir, destfile, dirs_exist_ok=True) 

2. 移動文件或目錄

語法:shutil.move(src, dst)

示例:

import os
import shutil

dirpath    = os.path.dirname(os.path.realpath(__file__))
sourcedir  = os.path.join(dirpath, "shutil_a")
sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        
destdir    = os.path.join(dirpath, "shutil_b")
shutil.move(sourcefile, destdir)
shutil.move(destdir, sourcedir)

3. 刪除文件和目錄

刪除某個文件使用 os 模塊提供的remove和unlink方法:

  • os.remove(path)
  • os.unlink(path)

刪除目錄使用 shutil.rmtree 方法:

import os
import shutil

dirpath    = os.path.dirname(os.path.realpath(__file__))     
destdir    = os.path.join(dirpath, "shutil_b")
shutil.rmtree(destdir)

二、shutil文件壓縮、解壓

shutil庫也支持文件壓縮、解壓操作,這個功能在Python 3.2版本引入。

1. 壓縮文件

語法格式:

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
  • base_name:壓縮包文件名
  • format:壓縮包格式,支持zip,tar,bztar,gztar,xztar格式,可使用shutil.get_archive_formats()方法查看
  • root_dir:要壓縮文件路徑的根目錄(默認當前目錄)
  • base_dir:相對於root_dir的壓縮文件路徑(默認當前目錄)

示例:

import os
import shutil
#Python小白學習交流羣:725638078
dirpath    = os.path.dirname(os.path.realpath(__file__))
archive_name  = os.path.join(dirpath, "shutil_a")
root_dir = archive_name
shutil.make_archive(archive_name, 'zip', root_dir)

2. 解壓文件

語法格式:

shutil.unpack_archive(filename[, extract_dir[, format]])

示例:

import os
import shutil

dirpath      = os.path.dirname(os.path.realpath(__file__))
archive_name = os.path.join(dirpath, "shutil_a.zip")
extract_dir  = os.path.join(dirpath, "shutil_a")   
shutil.unpack_archive(archive_name, extract_dir, 'zip')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章