python shutil模块

Doc: https://docs.python.org/2/library/shutil.html#module-shutil

shutil模块包涵了对文件和文件夹的: 复制,移动,删除, 打包,压缩 等操作。

shutil.copyfileobj(fsrcObj, fdstObj [, length])

对文件对象进行复制,因为操作的文件对象需要用open()打开才是一个对象,所以这个函数并不好用。

程序:

结果:

 

shutil.copyfile(src, dst)

复制文件,从src到dst, 只复制文件内容。 权限, 修改时间等metadata不复制。

程序:

结果:

 

shutil.copymode(src, dst)

只复制文件的权限。由于是只把权限复制过去,所以src, dst 两个文件都必须已经存在,如果dst不存在,就会报错:

OSError: [Errno 2] No such file or directory: ‘003_cp’

程序:

结果:

 

shutil.copystat(src, dst)

只复制修改时间等metadata。 也是需要src, dst两文件必须已经存在。

程序:

结果:

 

shutil.copy(src, dst)

复制文件内容, 权限。 但修改时间等metadata不复制。 如果dst为文件夹,就在dst文件夹下创建与src同名文件。

这个函数蛮好的,可以看出复制时的时间,如果要和源文件保持一样的时间,可以用下面copy2()函数。

程序:

结果:

 

shutil.copy2(src, dst)

复制文件内容,权限,修改时间等metadata。

程序:

结果:

 

shutil.copytree(src, dst, symlink=False, ignore=None)

复制文件夹src下整个树到dst。

symlink=False时, 复制符号链接时,把符号链接的文件复制过来,而不是保持一个简单的符号链接。

symlink=True时, 复制符号链接时,仍然是一个符号链接。

ignore 可以把某些文件忽略掉,不复制。

程序:

结果:

程序:

结果:

程序:

结果:

 

shutil.rmtree(path[, ignore_errors[, onerror]])

删除目录树。

程序:

结果:

 

shutil.move(src, dst)

移动文件或文件夹。

程序:

结果:

 

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

打包。

程序:

结果:

 

Github: https://github.com/allenmo/python_study/tree/master/shutil