shutil 高级文件操作
High-level file operations 高级的文件操作模块,官网:https://docs.python.org/2/library/shutil.html#
os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作。比如说:绝对路径,父目录…… 但是,os文件的操作还应该包含移动 复制 打包 压缩 解压等操作,这些os模块都没有提供。
而本章所讲的shutil则就是对os中文件操作的补充。--移动 复制 打包 压缩 解压,
注意即便是更高级别的文件复制函数(shutil.copy(),shutil.copy2())也不能复制所有文件的元数据。这意味着在POSIX平台上,文件的所有者和组以及访问控制列表都将丢失。在Mac OS中资源fork和其他元数据无法使用。这意味着资源将丢失,文件类型和创建者代码将不正确。在Windows上,文件所有者,ACL和备用数据流不会被复制。
拷贝文件
shutil.copyfile(src, dst):复制文件内容(不包含元数据)从src到dst。dst 必须是完整的目标文件名;拷贝目录参见shutil.copy()。如果src和dst是同一文件,就会引发错误shutil.Error。dst必须是可写的,否则将引发异常IOError。如果dst已经存在,它会被替换。特殊文件,例如字符或块设备和管道不能使用此功能,因为copyfile会打开并阅读文件。 src和dst的是字符串形式的路径名。
copyfile()调用了底函数层copyfileobj()。
shutil.copyfileobj(fsrc, fdst[, length]):复制文件内容(不包含元数据)从类文件对象src到类文件对dst。可选参数length指定缓冲区的大小,负数表示一次性读入。默认会把数据切分成小块拷贝,以免占用太多内存。注意:拷贝是从fsrc的当前文件开始。
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
shutil.copyfileobj(fsrc, fdst[, length])
Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks.
含义:拷贝fsrc类文件对象到fdst类文件对象
shutil.copyfile(src, dst)
Copy the contents (no metadata) of the file named src to a file named dst.
含义:拷贝src文件内容(不包含元数据)到目标dst文件
shutil.copytree(src, dst, symlinks=False, ignore=None)
Recursively copy an entire directory tree rooted at src.
含义:递归拷贝以src为根目录的整个目录树到目标目录
shutil.rmtree(path[, ignore_errors[, onerror]])
Delete an entire directory tree.
含义:删除整个目录树
shutil.move(src, dst)
Recursively move a file or directory (src) to another location (dst).
含义:移动一个文件或目录到另一个位置(同目录也可以用来修改名字)。
shutil.copymode(src, dst)
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings.
含义:从源文件拷贝权限位到目标文件,文件内容、所有者、组不受影响。
shutil.copystat(src, dst)
Copy the permission bits, last access time, last modification time, and flags from src to dst. The file contents, owner, and group are unaffected.
含义:从源文件拷贝权限位、最后访问时间、最后修改时间、flags到目标文件,文件内容、所有者、组不受影响。
shutil.copy(src, dst)
Copy the file src to the file or directory dst.
含义:拷贝源文件到文件或目录。
shutil.copy2(src, dst)
Similar to shutil.copy(), but metadata is copied as well – in fact, this is just shutil.copy() followed by copystat(). This is similar to the Unix command cp -p.
含义:和shutil.copy()相似,但是也会拷贝元数据,实际上只是调用shutil.copy()后接着调用copystart()。
#!/usr/bin/python3 -B import shutil
import os
import datetime
import subprocess def main():
base_src_path = "/home/dsw/work/src"
base_dst_path = "./backup"
copy_dir = ["scene", "layer", "logic", "tools"]
ignore_pattern = shutil.ignore_patterns("*.o", "*.a") if os.path.exists(base_dst_path):
shutil.rmtree(base_dst_path)
os.mkdir(base_dst_path) for entry in copy_dir:
src = os.path.join(base_src_path, entry)
dst = os.path.join(base_dst_path, entry)
shutil.copytree(src, dst, ignore=ignore_pattern) t = datetime.datetime.now()
tar_name = t.strftime("game-%m-%d-%H-%M.tar.gz")
cmd = "tar -cf {0} ./backup/*".format(tar_name)
subprocess.call(cmd, shell=True) if __name__ == '__main__':
main()
压缩解压
2.7以后的版本提供了压缩和解压功能。
shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]):创建归档文件(如ZIP或TAR),返回其名字。base_name文件名。format压缩格式,“zip”, “tar”, “bztar” or “gztar”。root_dir压缩的根目录。base_dir开始压缩的目录。root_dir 和 base_dir默认都是当前目录。所有者和组默认为当前用户和组;logger为logging.Logger的实例。
shutil.get_archive_formats():返回支持的格式列表。默认支持:
In [3]: shutil.get_archive_formats()
Out[3]:
[('bztar', "bzip2'ed tar-file"),
('gztar', "gzip'ed tar-file"),
('tar', 'uncompressed tar file'),
('zip', 'ZIP file')]
通过使用register_archive_format()可以增加新格式。
shutil.register_archive_format(name, function[, extra_args[, description]]):注册一个文件格式,不常用。
shutil.unregister_archive_format(name):移除文件格式,不常用。
压缩实例:
#!/usr/bin/python3 -B import os
from shutil import make_archive def main():
make_archive("backup", 'tar', "/home/dsw/work") #将/home/dsw/work目录下的文件备份 if __name__ == '__main__':
main()
shutil 高级文件操作的更多相关文章
- python3之shutil高级文件操作
1.shutil高级文件操作模块 shutil模块提供了大量的文件的高级操作.特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作.对单个文件的操作也可参见os模块. 2.shutil模块的拷 ...
- python模块之shutil高级文件操作
简介 shutil模块提供了大量的文件的高级操作.特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作.对单个文件的操作也可参见os模块. 注意即便是更高级别的文件复制函数(shutil.co ...
- Python的高级文件操作(shutil模块)
Python的高级文件操作(shutil模块) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果让我们用python的文件处理来进行文件拷贝,想必很多小伙伴的思路是:使用打开2个 ...
- 第3章 文件I/O(7)_高级文件操作:存储映射
8. 高级文件操作:存储映射 (1)概念: 存储映射是一个磁盘文件与存储空间的一个缓存相映射,对缓存数据的读写就相应的完成了文件的读写. (2)mmap和munmap函数 头文件 #include&l ...
- 第3章 文件I/O(6)_高级文件操作:文件锁
7. 高级文件操作:文件锁 (1)文件锁分类 分类依据 类型 说明 按功能分 共享读锁 文件描述符必须读打开 一个进程上了读锁,共它进程也可以上读锁进行读取 独占写锁 文件描述符必须写打开 一个进程上 ...
- 【Python】 高级文件操作 shutil
shutil 很多时候,我想要对文件进行重命名,删除,创建等操作的时候的想法就是用subprocess开一个子进程来处理,但是实际上shutil可以更加方便地提供os的文件操作接口,从而可以一条语句搞 ...
- python- shutil 高级文件操作
简介 shutil模块提供了大量的文件的高级操作.特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作.对单个文件的操作也可参见os模块. 拷贝文件 shutil.copyfile(src, ...
- Python3-shutil模块-高级文件操作
Python3中的shutil模块提供了对文件和容器文件的一些高级操作 shutil.copy(src, dst) 拷贝文件,src和dst为路径的字符串表示,copy()会复制文件数据和文件权限,但 ...
- JS高级——文件操作
https://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/12/2208589.html https://blog.csdn.net/pl16 ...
随机推荐
- SharePoint 站点导航Web部件
SharePoint 站点导航Web部件 SharePoint 站点导航Web部件可以以树状图显示站点层级关系.便于管理. 效果:点击子网站能够跳转过去.我这里建的少. ...
- macos下安装oh-my-zsh和zsh-autosuggestion
1:安装oh-my-zsh sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/mast ...
- Tensorflow中的name_scope和variable_scope
Tensorflow是一个编程模型,几乎成为了一种编程语言(里面有变量.有操作......). Tensorflow编程分为两个阶段:构图阶段+运行时. Tensorflow构图阶段其实就是在对图进行 ...
- DPDK的安装与绑定网卡(转)
from:http://www.cnblogs.com/mylinuxer/p/4274178.html DPDK的安装与绑定网卡 DPDK的安装有两种方法: 第一种是使用dpdk/tools/set ...
- 淘宝JAVA中间件Diamond详解之简介&快速使用 管理持久配置的系统
http://my.oschina.net/u/435621/blog/270483?p=1 淘宝JAVA中间件Diamond详解(一)---简介&快速使用 大家好,今天开始为大家带来我们通用 ...
- Python学习笔记(七)—— 循环
一.for ... in ... 循环 1.语法 names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) (1)需要有冒号 ...
- 在Linux上yum安装运行Redis,只能安装2.4.10(主从)
Installing Redis on CentOS 6.4 First, install the epel repo sudo rpm -Uvh http://download.fedoraproj ...
- Bitnami Redmine 中文附件名 报错修复
最近自己在服务器上搭了个redmine,用的是Bitnami的一键安装程序. 搭好后,运行得不错,居然还增加了负载均衡. 某天上传中文附件,打开报内部错误,去redmine官网看了下,果然有这个问题, ...
- 【转载,待整理】初学 springmvc整合shiro
1. shiro认证流程理解 2. 整合过程 http://blog.csdn.net/dawangxiong123/article/details/53020424 http://blog.csdn ...
- Android工具类-关于网络、状态的工具类
下方是一个很好的监测网络.状态的工具类 public class NetworkUtils { /** * 网络是否可用 * * @param activity * @return */ public ...