Python os模块

来源:互联网 发布:javascript 策略模式 编辑:程序博客网 时间:2024/06/18 12:36

        Python的os模块提供各种操作系统的接口,实现了Python跨平台操作。os模块除了可以对进程和进程的运行环境进行管理外,还可以对文件系统进行操作。os模块的所有操作会触发OSError异常,并且有些函数只有对特定的操作系统才会起用。

>>> # os 模块>>> # 导入os模块>>> import os>>> # os.name ---> 系统名称>>> os.name'nt'>>> #目前已被注册的系统有:>>> #POSIX,nt,os2,ce,java,riscos>>> #os.environ:返回系统环境变量的字典>>> os.environ['HOME']'C:\\Users\\Administrator'

        os模块常见文件或目录操作函数:

>>> #当前目录>>> os.getcwd()'f:\\tmp'>>> #改变工作目录>>> os.chdir('f:\\tmp')>>> #创建目录>>> os.mkdir('test')>>> #列出指定目录文件>>> os.listdir(os.getcwd())['f.txt', 'test']>>> #重命名>>> os.rename('f.txt','temp.txt')>>> os.listdir(os.getcwd())['temp.txt', 'test']>>> #文件信息>>> os.stat('temp.txt')nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=0L, st_atime=1416655844L, st_mtime=1416655844L, st_ctime=1416655844L)>>> #删除文件>>> os.remove('temp.txt')>>> os.listdir(os.getcwd())['test']>>> #删除目录>>> os.rmdir('test')>>> os.listdir(os.getcwd())[]

        os.path模块常用路径名访问函数

>>> #去掉路径,返回文件名>>> os.path.basename('test.txt')'test.txt'>>> #去掉文件名,返回目录路径>>> os.path.dirname('temp\\temp.txt')'temp'>>> #将分离的各部分连接成一个路径名>>> os.path.join(os.getcwd(),'file.txt')'f:\\tmp\\file.txt'>>> os.path.abspath('test.txt') #绝对路径'f:\\tmp\\test.txt'>>> os.path.split('test.txt') #返回路径名,文件名元组('', 'test.txt')>>> os.path.splitext('test.txt') #返回路径名,扩展名元组('test', '.txt')>>> os.path.getatime('test.txt')1416657769.433169>>> #getctime() --->创建时间>>> #getmtime() --->最近修改时间>>> #getsize() --->文件大小>>> os.path.exists('test.txt') #文件或目录是否存在True>>> #isabs() --->是否绝对路径>>> #isdir() --->是否存在且为路径>>> #isfile() --->是否存在且为文件
        os模块分隔符

>>> #此处是windows环境下的分隔符>>> os.linesep'\r\n'>>> os.sep  #分隔文件路径名字符串'\\'>>> os.pathsep  #分隔文件路径字符串';'>>> os.curdir  #当前工作目录字符串'.'>>> os.pardir  #当前工作目录父目录字符串'..'

        本文所述的OS模块也还是当中的小部分,再学,再用……




0 0
原创粉丝点击