python模块-shutil模块

参考https://www.cnblogs.com/xiangsikai/p/7787101.html

os模块提供了对目录或者文件的新建、删除、查看文件属性,还提供了对文件以及目录的路径操作,比如说绝对路径、父目录……  但是文件的操作还应该包含移动、复制、打包、压缩、解压等操作,这些功能os模块没有提供。

而shutil模块则是对文件操作的补充,即移动、复制、打包、压缩、解压等操作。

1.只拷贝文件内容:shutil.copyfileobj(fsrc, fdst[, length]),相当于用原文件的内容覆盖目标文件的内容

import shutil
f1=open('a.ini','r')
f2=open('b.ini','w')
shutil.copyfileobj(f1,f2)

原文件要以读的模式打开,目标文件要以写的模式打开

2.拷贝文件:shutil.copyfile(src, dst),相当于创建一个空的目标文件,再把原文件内容覆盖到目标文件

import shutil
shutil.copyfile('a.ini','b.ini')

copyfile不需要打开文件

3.拷贝权限:shutil.copymode(src, dst)

import shutil
shutil.copymode('a.ini','b.ini')

要求目标文件存在

扫描二维码关注公众号,回复: 4348026 查看本文章

4.拷贝状态信息:shutil.copystat(src, dst),包括创建、访问和修改时间等

import shutil
shutil.copystat('a.ini','b.ini')

5.拷贝文件和权限:shutil.copy(src, dst),即先copyfile再copymode

import shutil
shutil.copy('a.ini','b.ini')

6.拷贝文件和状态:shutil.copy2(src, dst),即先copyfile再copystat

import shutil
shutil.copy2('a.ini','b.ini')

常用模块 https://www.jb51.net/article/135049.htm

猜你喜欢

转载自www.cnblogs.com/Forever77/p/10056357.html