码迷,mamicode.com
首页 > 编程语言 > 详细

Python shutil模块

时间:2017-11-05 13:17:58      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:打包   copy   压缩   pre   pen   write   alt   test   copyfile   

 

shutil模块

 

一.shutil模块

主要作用与拷贝文件用的。

1.shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。

import shutil

f1 = open("1.txt",encoding="utf-8")

f2 = open("2.txt","w",encoding="utf-8")

shutil.copyfileobj(f1,f2)

 

 

2.shutil.copyfile(文件1,文件2):不用打开文件,直接用文件名进行覆盖copy。

import shutil

shutil.copyfile("1.txt","3.txt")

 

 

3.shutil.copymode(文件1,文件2):之拷贝权限,内容组,用户,均不变。

def copymode(src,dst):
    """copy mode bits from src to dst"""
    if hasattr(os,chmod):
        st = os.stat(stc)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst,mode)

 

 

 

4.shutil.copystat(文件1,文件):只拷贝了权限。

 技术分享

 

 

5.shutil.copy(文件1,文件2):拷贝文件和权限都进行copy。

 技术分享

 

 

6.shutil.copy2(文件1,文件2):拷贝了文件和状态信息。

 

7.shutil.copytree(源目录,目标目录):可以递归copy多个目录到指定目录下。

 技术分享

 

 

8.shutil.rmtree(目标目录):可以递归删除目录下的目录及文件。

 

9.shutil.move(源文件,指定路径):递归移动一个文件。

 

10.shutil.make_archive():可以压缩,打包文件。

import shutil

shutil.make_archive("shutil_archive_test","zip","D:\新建文件夹 (2)")

 

技术分享

技术分享

 

 

 

 技术分享

 

 技术分享

 

 

 

 

第二种方法:

import zipfile

z = zipfile.ZipFile("day5.zip","w")

z.write("a")

 

 

解压:

z.extractall(“a”)

 

Python shutil模块

标签:打包   copy   压缩   pre   pen   write   alt   test   copyfile   

原文地址:http://www.cnblogs.com/xiangsikai/p/7787101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!