python os模块

来源:互联网 发布:网络的监控摄像头 编辑:程序博客网 时间:2024/06/05 07:51

OS模块可以实现目录的创建、修改、遍历等功能

os:

常用的属性、方法:

1、os.name
输出字符串指示正在使用的平台。如果是window 则用'nt'表示,对于Linux/Unix用户,它是'posix'。
2、os.getcwd()
函数得到当前工作目录,即当前Python脚本文件工作的(所在)目录路径。
3、os.listdir(path)
返回指定目录下的所有文件和文件夹的名字。
4、os.remove(path)

删除一个文件。如果path是一个文件夹将会抛出OSError异常。

5、os.rmdir(path)
删除path指定的空目录,如果目录非空会抛出OSError异常 os.rmdir('test')
     os.removedirs(path)
删除多级目录  os.removedirs('/a/b/test')

6、os.chdir(path) 
当前目录切换到指定目录中。path为要切换的新路径。允许访问返回true  
os.chdir('/')切换到根目录
os.chdir('.')切换到当前目录

7、os.mkdir(path[,mode])  
以数字权限模式创建目录。path要创建的目录,mode要为目录设置的权限数字模式
     os.makedirs(name,mode)
创建多级目录

8、os.curdir  
返回当前目录

9、os.system()
运行shell命令。eg:os.system('cmd') #启动dos

10、os.access(path,mode)  
path要检测是否有访问权限的路径。

                mode:mode取值为F_OK,R_OK, W_OK,X_OK等
                os.F_OK: 作为access()的mode参数,测试path是否存在。
                os.R_OK: 包含在access()的mode参数中 , 测试path是否可读。
                os.W_OK 包含在access()的mode参数中 , 测试path是否可写。
                os.X_OK 包含在access()的mode参数中 ,测试path是否可执行。

11、 os.sep          操作系统特定的路径分割符。
          
os.linesep    字符串给出当前平台使用的行终止符
>>> os.linesep
'\r\n'    #Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
>>> os.sep
'\\'      #Windows

12、os.walk(path)
返回一个元组。元组中有三个元素,分别表示每次遍历的路径名,目录列表,文件列表

os.path:

1、os.path.isfile()、os.path.isdir()、os.path.isabs()
函数分别检验给出的路径是一个文件还是目录还是绝对路径。
>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile('a.txt')
False
2、os.path.exists()
函数用来检验给出的路径(文件或目录)是否存在
>>> os.path.exists('C:\\Python25\\abc.txt')
False
>>> os.path.exists('C:\\Python25')
True

3、os.path.abspath(name)
获得绝对路径

5、os.path.samefile(path1,path2)

判断两个路径是否指向同一个文件

6、getatime()  

      返回最近访问时间

      getctime()  

      返回文件创建时间

      getmtime() 

      返回最近文件修改时间

7、os.path.getsize(file)

获得文件大小(字节),如果file是目录则返回0

8、os.path.split()
函数返回一个路径的目录名和文件名(以元组的形式返回)
>>> os.path.split('C:\\Python25\\abc.txt')
('C:\\Python25', 'abc.txt')

9、os.path.splitext()
分离文件名与扩展名(以元组的形式返回)
>>> os.path.splitext('a.txt')
('a', '.txt')
10、os.path.join(path,file)
连接目录与文件名或目录
>>> os.path.join('c:\\Python','a.txt')
'c:\\Python\\a.txt'
>>> os.path.join('c:\\Python','f1')
'c:\\Python\\f1'
>>> 
11、os.path.basename(path)
返回文件名
>>> os.path.basename('a.txt')
'a.txt'
>>> os.path.basename('c:\\Python\\a.txt')
'a.txt'
>>> 
12、os.path.dirname(path)
返回文件路径
>>> os.path.dirname('c:\\Python\\a.txt')
'c:\\Python'


0 0
原创粉丝点击