python模块系列之 - os , os.path,shutil

来源:互联网 发布:网络直播app电视版 编辑:程序博客网 时间:2024/06/05 04:31

os

os模块对操作系统的特定模块进行了一个封装,包括posix, nt 和 mac, os提供的API函数在所有的平台上使用方法都是一样的,因此使用os模块提供了平台的移植性。但并不是所有的函数在所有的平台上都可以使用。
常用OS方法
序号函数说明1os.access(path,mode)按照mode指定的权限访问文件2os.chmod(path,mode)改变文件的访问权限。Mode用UNIX系统中的权限代号表示3os.open(filename,flag[,mode=0777]按照mode指定的权限打开文件。默认情况下给所有用户读、写、执行权限4os.remove(path)删除path指定的文件5os.rename(old,new)重命名文件或目录.  Old表示原文件或目录, new表示新文件或目录6os.stat(path)返回path指定文件的所有属性7os.fstat(path)返回打开的文件的所有属性8os.lseek(fd,pos,how)设置文件的当前位置,返回当前位置的字节数9os.start(filepath,[,operation])启动关联程序打开文件。例如:打开的是1个html文件,将启动IE浏览器10os.tmpfile()创建1个临时文件,文件创建在操作系统的临时目录中11os.mkdir(path,[mode=0777])创建path指定的一个目录12os.makedirs(name,mode=511)创建多级目录,name表示path1/path213os.rmdir(path)删除path指定的目录14os.removedirs(path)删除path指定的多级目录15os.listdir(path)返回path指定的目录下的所有文件名16os.getcwd()返回当前的工作目录17os.chdir(path)将当前的目录改变为path指定的目录18os.walk(top,topdown=True,onerror=None)top:要遍历的路径
官网链接: https://docs.python.org/3/library/os.html?highlight=os#module-os

os.path

使用os.path模块中包含的函数能很容易的在不同平台上进行文件的操作。
序号函数解释1os.path.abspath(path) 返回绝对路径2os.path.basename(path) 返回文件名3os.path.commonprefix(list) 返回list(多个路径)中,所有path共有的最长的路径。4os.path.dirname(path) 返回文件路径5os.path.exists(path)  路径存在则返回True,路径损坏返回False6os.path.lexists  路径存在则返回True,路径损坏也返回True7os.path.expanduser(path)  把path中包含的"~"和"~user"转换成用户目录8os.path.expandvars(path)  根据环境变量的值替换path中包含的”$name”和”${name}”9os.path.getatime(path)  返回最后一次进入此path的时间。10os.path.getmtime(path)  返回在此path下最后一次修改的时间。11os.path.getctime(path)  返回path的大小12os.path.getsize(path)  返回文件大小,如果文件不存在就返回错误13os.path.isabs(path)  判断是否为绝对路径14os.path.isfile(path)  判断路径是否为文件15os.path.isdir(path)  判断路径是否为目录16os.path.islink(path)  判断路径是否为链接17os.path.ismount(path)  判断路径是否为挂载点()18os.path.join(path1[, path2[, ...]])  把目录和文件名合成一个路径19os.path.normcase(path)  转换path的大小写和斜杠20os.path.normpath(path)  规范path字符串形式21os.path.realpath(path)  返回path的真实路径22os.path.relpath(path[, start])  从start开始计算相对路径23os.path.samefile(path1, path2)  判断目录或文件是否相同24os.path.sameopenfile(fp1, fp2)  判断fp1和fp2是否指向同一文件25os.path.samestat(stat1, stat2)  判断stat tuple stat1和stat2是否指向同一个文件26os.path.split(path)  把路径分割成dirname和basename,返回一个元组27os.path.splitdrive(path)   一般用在windows下,返回驱动器名和路径组成的元组28os.path.splitext(path)  分割路径,返回路径名和文件扩展名的元组29os.path.splitunc(path)  把路径分割为加载点与文件30os.path.walk(path, visit, arg)  遍历path,进入每个目录都调用visit函数,visit函数必须有
官网链接:https://docs.python.org/3/library/os.path.html?highlight=os#module-os.path

sys

sys.argv         命令行参数List,第一个元素程序本身路径sys.exit(n)     退出程序,正常退出时exit(0)sys.version    获取Python解释程序的版本信息sys.maxint      最大的Int值sys.path         返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform   返回操作系统平台名称sys.stdout.write('please:')val = sys.stdin.readline()[:-1]

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