python模块系列之 - os , os.path,shutil
来源:互联网 发布:网络直播app电视版 编辑:程序博客网 时间:2024/06/05 04:31
os
os模块对操作系统的特定模块进行了一个封装,包括posix, nt 和 mac, os提供的API函数在所有的平台上使用方法都是一样的,因此使用os模块提供了平台的移植性。但并不是所有的函数在所有的平台上都可以使用。
常用OS方法
官网链接: https://docs.python.org/3/library/os.html?highlight=os#module-os
os.path
使用os.path模块中包含的函数能很容易的在不同平台上进行文件的操作。
官网链接:https://docs.python.org/3/library/os.path.html?highlight=os#module-os.path
sys
shutil
shutil模块提供高级文件操作,包括文件的删除、拷贝等,也支持文件压缩。
copy()
copy(src,dst) 拷贝文件,不拷贝元数据,返回拷贝的目标文件地址;目标dst(可以是文件,也可以是目录),若dst存在则覆盖。 若src 不存在则报错 FileNotFoundError, 若src 与 dst 为同一个文件报错:SameFileError
shutil.copy('test.txt', 'test') # test/test.txt
copy2()
copy2(src,dst) 同copy(),区别是拷贝时也拷贝元数据(文件属性、创建时间等信息)实际是先copy,在copystat ,等同与unix命令: cp -p
shutil.copy2('test2.txt','test_copy2.txt') # test_copy2.txt
copyfile()
copyfile(src,dst.length) 与copy类似,只是目的必须是文件名, length指定读入缓存区的长度,这样将文件分片,以免占用太多内存,内部调用 copyfileobj()print(shutil.copyfile('test.txt','test_copyfile.txt')) # test_copyfile.txt
copyfileobj()
copyfileobj(fsrc,fdst,length) 与copyfile类似, src与dst为文件对象 ,length为读入缓存的大小,分片
src = 'test2.txt'dst = 'test_copyfileobj.txt'with open(src,'rb') as fsrc: with open(dst,'wb') as fdst: shutil.copyfileobj(fsrc,fdst,length=1024)
copymode()
copymode(src,dst) 拷贝源文件src的权限,使dst文件的读写权限 -rw-rw-r-- 与src一致,文件的所属用户和组不改变
shutil.copyfile('/tmp/ptest/src.txt','/tmp/ptest/dst_copyfile.txt')# 执行前:# -rw-r--r-- 1 root root 9 Feb 1 13:27 dst_copyfile.txt# -rw-rw-r-- 1 tibco tibco 9 Feb 1 13:25 src.txtshutil.copymode('/tmp/ptest/src.txt','/tmp/ptest/dst_copyfile.txt')# 执行后:# -rw-rw-r-- 1 root root 9 Feb 1 13:27 dst_copyfile.txt# -rw-rw-r-- 1 tibco tibco 9 Feb 1 13:25 src.txt
copystat()
copystat(src,dst) 拷贝源文件src的属性到目标文件,包括:文件权限、创建时间、最后修改时间,文件所欲用户和组不变.
shutil.copystat('/tmp/ptest/src.txt','/tmp/ptest/dst_copyfile.txt')# 执行前# -rw-rw-r-- 1 root root 9 Feb 1 13:27 dst_copyfile.txt# -rwx------ 1 tibco tibco 9 Feb 1 13:25 src.txt# 执行后# -rwx------ 1 root root 9 Feb 1 13:25 dst_copyfile.txt# -rwx------ 1 tibco tibco 9 Feb 1 13:25 src.txt
copytree()
拷贝目录树,简单的说就是拷贝源目录及其下面的所有子目录及文件到dst下,目标不能是存在的目录
shutil.copytree('/tmp/ptest/dir1','/tmp/ptest/dir2')执行前:ptest├── dir1│ ├── dir1_1│ │ ├── dir1_1_1│ │ │ ├── file1-1-1│ │ │ └── file1-1-3│ │ ├── file1-1│ │ └── file1-2│ └── file-1├── dst_copyfile.txt└── src.txt执行后ptest|-- dir1| |-- dir1_1| | |-- dir1_1_1| | | |-- file1-1-1| | | `-- file1-1-3| | |-- file1-1| | `-- file1-2| `-- file-1|-- dir2| |-- dir1_1| | |-- dir1_1_1| | | |-- file1-1-1| | | `-- file1-1-3| | |-- file1-1| | `-- file1-2| `-- file-1|-- dst_copyfile.txt`-- src.txt
rmtree()
rmtree()
move()
shutil.move("test2.txt","test") 移动文件。dst可以是文件名也可以是目录,目标文件存在则覆盖
文件压缩
get_archive_formats()
返回shutil支持的压缩格式
print(shutil.get_archive_formats())# [('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), ('zip', 'ZIP file')]
make_archive()
make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None)文件压缩,支持的格式包括:bztar,gztar,tar,zip
参数说明:
base_name:要创建的压缩文件的存放路径及名称,如aa.tar 或 /tmp/archinve/aaa.tar ,如果指定路径则默认在当前路径下
format:压缩的文件格式,比如 "zip", "tar", "bztar" or "gztar".
root_dir: 要压缩的文件夹路径,默认当前路径
base_dir:开始压缩的目录
owner: 用户 默认当前用户
group:用户组,默认当前用户组
logger:日志对象,logging.Logger对象
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError, "unknown archive format '%s'" % format func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename方法操作:
#将/tmp/ptest/dir2用gztar进行压缩,文件名为aaashutil.make_archive('/tmp/ptest/aaa','gztar',root_dir='/tmp/ptest/dir2')如果要压缩的目录中的文件为空,则不会压缩
unpack_archive()
unpack_archive(filename,extra_dir,format)解压缩文件
filename:要解压缩的文件名
extra_dir:解压的路径
format:解压缩的文件的文件格式 "zip", "tar", "bztar" or "gztar".
# 将/tmp/ptest/aaa.tar.gz解压缩的/tmp/ptest下shutil.unpack_archive('/tmp/ptest/aaa.tar.gz','/tmp/ptest/','gztar')
disk_usage
disk_usage(path) python3.x才有的新功能。返回指定磁盘的使用情况,包括:total, used, free. 支持:unix,windows
print(shutil.disk_usage(("d:/")))#result:usage(total=209715195904, used=14263074816, free=195452121088)
chown()
chown(path,user,group) 给指定的path路径修改所属用户和组,类似于chown path user:gropu 。python3.x中的新功能,仅支持 unix
shutil.chown('/tmp/ptest/dir1.tar.gz',user='root',group='root')#执行前:-rw-rw-r-- 1 tibco tibco 258 Feb 1 15:09 dir1.tar.gz# 执行后-rw-rw-r-- 1 root root 258 Feb 1 15:09 dir1.tar.gz
更多功能:https://docs.python.org/3/library/shutil.html?highlight=shutil#module-shutil
0 0
- python模块系列之 - os , os.path,shutil
- Python os.path模块和shutil模块
- Python--os模块--shutil
- python shutil os os.path模块 open总结
- python模块之os和os.path
- python之os.path模块
- python之os.path模块
- Python--os模块和shutil模块
- Python的os和shutil模块
- python的 os 和 shutil 模块
- Python中 os、shutil 模块实用方法
- Python中os和shutil模块
- python OS shutil 模块中的函数
- python常见模块命令os,sys,shutil
- Python文件操作os,shutil模块
- Python模块: 文件和目录os+shutil
- python类库31[文件和目录os+os.path+shutil]
- python类库[文件和目录os+os.path+shutil]
- oracle数据库表备份和表恢复 怎样将Oracle一张表的多个字段更新到另一张表中去
- Android 6.0 Marshmallow SettingsProvider
- findViewById返回为NULL
- 关于CSV文件导入到数据的方法以及遇到的问题和解决方案
- 注解不能自动注入
- python模块系列之 - os , os.path,shutil
- Python基础教程笔记——列表和元组
- java读取word文档
- 了解Web及网络基础
- Myeclipse中 报出The type javax.servlet.http.HttpServlet cannot be resolved. It is indirect错误
- Structs2或SSH项目在Action中获取session对象
- 为什么这么多人喜欢做饭而不喜欢洗碗?
- 生成器表达式(Generator expression)和列表表达式
- Volley框架学习(一)实现Json字符串请求