python之os库

来源:互联网 发布:剑网三dbm数据那个好 编辑:程序博客网 时间:2024/05/01 12:58

1.常用属性与方法

名称 功能 os.name 返回使用的平台 os.getcwd() 获得当前目录 os.listdir(mydir) 返回指定目录下所有文件和目录名 os.remove(filename) 删除文件(不能删除目录) os.system(command) 运行shell命令 os.sep 表示系统路径分隔符,可以自行设置 os.linesep 表示行终止符,可以自行设置 os.path.split(filepath) 返回一个路径的目录名和文件名 os.path.isfile(filepath) 检验给出的路径是否为文件 os.path.isdir(filepath) 检验给出的路径是否为目录 os.path.exists(filepath) 检验给出的路径是否存在 os.path.abspath(name) 获得绝对路径 os.path.normpath(pathname) 规范pathname字符串形式 os.path.getsize(filepath) 获得文件大小,如果filepath是目录返回0L os.path.splitext(filename) 分离文件名与扩展名 os.path.join(path,name) 连接目录与文件名或目录 os.path.basename(pathname) 返回文件名 os.path.dirname(pathname) 返回文件路径

2.一个例子
假如在/home/wpp下有一个test_os.py的文件,其内容如下

#!/usr/bin/env pythonimport os                                                                   print os.name#posixprint os.getcwd()#/home/wppprint os.listdir(os.getcwd())#结果太长,在此就不给出了print os.path.split(os.getcwd())#('/home','wpp') #值得注意的是此方法只是简单的对路径进行了分割#并没有保证第二个元素一定是文件,如wppprint os.path.isfile(os.getcwd())#Falseprint os.path.isdir(os.getcwd())#Trueprint os.path.exists(os.getcwd())#Trueprint os.path.abspath('test_os.py')#/home/wpp/test_os.pyprint os.path.normpath(os.getcwd())#/home/wppprint os.path.getsize('test_os.py')#508print os.path.splitext('test_os.py')#('test_os','.py')print os.path.join(os.getcwd(),'test.sh')#/home/wpp/test.shprint os.path.basename('/home/wpp/test_os.py')#test_os.pyprint os.path.dirname('/home/wpp/test_os.py')#/home/wpp
0 0
原创粉丝点击