原文:https://www.cnblogs.com/wang-yc/p/5625046.html
一. 簡介
shutil 是高級的文件,文件夾,壓縮包處理模塊。
二. 使用
shutil.copyfileobj(fsrc, fdst[, length])
將文件內容拷貝到另一個文件中
1
2
3
|
import
shutil
shutil.copyfileobj(
open
(
'old.xml'
,
'r'
),
open
(
'new.xml'
,
'w'
))
|
shutil.copyfile(src, dst)
拷貝文件
1
|
shutil.copyfile(
'f1.log'
,
'f2.log'
)
|
shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變
1
|
shutil.copymode(
'f1.log'
,
'f2.log'
)
|
shutil.copystat(src, dst)
僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags
1
|
shutil.copystat(
'f1.log'
,
'f2.log'
)
|
shutil.copy(src, dst)
拷貝文件和權限
1
|
shutil.copy(
'f1.log'
,
'f2.log'
)
|
shutil.copy2(src, dst)
拷貝文件和狀態信息
1
|
shutil.copy2(
'f1.log'
,
'f2.log'
)
|
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾
1
2
3
|
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]])
遞歸的去刪除文件
1
|
shutil.rmtree(
'folder1'
)
|
shutil.move(src, dst)
遞歸的去移動文件,它類似mv命令,其實就是重命名。
1
|
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對象
1
2
3
4
5
6
7
8
|
#將 /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兩個模塊來進行的。
1
2
3
4
5
6
7
8
9
10
11
12
|
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()
|
1
2
3
4
5
6
7
8
9
10
11
12
|
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()
|