Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

python shutil 学习小结

$
0
0

shutil 按照字面可以理解为shell utility,官方说这是一个高阶的文件操作类库,包含了常见的复制、移动、删除、归档压缩操作,用起来很简单,不需要你自己再去调用os、tarfile、gzip等模块封装了。

操作前需要 import shutil

复制 #复制一个文件到一个文件或一个目录 In [83]: shutil.copy('a.py','b.py') In [84]: ll total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 b.py In [85]: pwd Out[85]: u'/tmp/test' In [86]: ll /root/test ls: cannot access /root/test: No such file or directory #把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接 In [87]: shutil.copytree('/tmp/test/','/root/te') /root/test.sql /root/test.sql.tar.gz In [87]: shutil.copytree('/tmp/test/','/root/test') In [88]: ll /root/test/ total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 b.py In [89]: ll /tmp/test total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 b.py In [90]: 移动或者重命名 #移动文件或重命名 In [90]: ll total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 b.py In [91]: shutil.move('b.py','c.py') In [92]: ll total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 c.py 删除 #递归删除一个目录以及目录内的所有内容 In [97]: ll /root/test/ total 8 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 b.py In [98]: shutil.rmtree('/root/test') In [99]: ll /root/test/ ls: cannot access /root/test/: No such file or directory 压缩归档 #把/tmp/test/z压缩归档到/root/z.tar.gz In [101]: ll total 12 -rw-r--r-- 1 root 998 Dec 15 14:50 a.py -rw-r--r-- 1 root 998 Dec 21 15:39 c.py drwxr-xr-x 2 root 4096 Dec 21 15:52 z/ In [102]: shutil.make_archive('/root/z','gztar','/tmp/test/z') Out[102]: '/root/z.tar.gz' In [103]: ll /root/z.tar.gz -rw-r--r-- 1 root 147 Dec 21 15:53 /root/z.tar.gz 参考资料:

python shutil 官网: https://docs.python.org/2/library/shutil.html

shutil模块 : http://xukaizijian.blog.163.com/blog/static/170433119201111414053801/

shutil 模块:高级文件操作: http://lijin-thu.github.io/11.%20useful%20tools/11.05%20shutil.html

Python shutil模块: http://521monkey.com/Python_shutil模块

← python glob 学习小结

Viewing all articles
Browse latest Browse all 9596

Trending Articles