Python shutil模块

说明:shutil是一个高级的文件操作模块,主要对文件提供移动、复制、打包、压缩、解压等操作。

1. shutil.copyfile   ## 拷贝文件

import shutil
shutil.copyfile('1.txt','2.txt')

2. shutil.copymode  #仅copy权限,不更改文件内容,组和用户

查看两个文件权限:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rw-r--r-- 1 www  www  0 12月 24 13:06 2.txt

运行命令:
import shutil
shutil.copyfile('1.txt','2.txt')

结果:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rwxr-xr-x 1 www  www  0 12月 24 13:06 2.txt

3. shutil.copy    ##复制文件的内容以及权限

查看两个文件信息:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rw-r--r-- 1 www  www  0 12月 24 13:06 2.txt

运行命令:
import shutil
shutil.copy('1.txt','2.txt')

结果:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rwxr-xr-x 1 www  www  21 12月 24 13:06 2.txt

4. shutil.copy2    # 复制文件的内容以及文件的所有状态信息,不改变用户和组

查看两个文件信息:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rw-r--r-- 1 www  www  0 12月 24 13:06 2.txt

运行命令:
import shutil
shutil.copy('1.txt','2.txt')

结果:
[root@master ~]# ll *.txt
-rwxr-xr-x 1 root root 21 12月 28 17:33 1.txt
-rwxr-xr-x 1 www  www  21 12月 24 17:33 2.txt

5. shutil.chown    ## 修改文件或者目录用户和组

shutil.chown('1.txt', 'www', 'www')

6. shutil.make_archive    #压缩打包

shutil.make_archive("wangzai", "gztar", root_dir="/root/client")   ## 默认压缩在当前目录下,不能压缩文件
## base_name 压缩包的文件名,也可以是压缩包路径
## zip 压缩包种类 (zip,tar,bztar,gztar)
## root_dir 要压缩的文件夹路径(默认当前路径)
原文地址:https://www.cnblogs.com/654wangzai321/p/8150913.html