一、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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549485.html
標籤:Python
上一篇:Python 元編程
