本文参照菜鸟教程,练习使用并动手改写了某些方法,仅供自己学习,如需详细了解请跳转菜鸟教程:
1. 检验权限模式
- os.access(path,mode)
参数:
返回值: 如果允许访问则返回 True,否则返回 False。
例子:
- import os, sys
- # 假定 /tmp/foo.txt 文件存在,并有读写权限
- ret = os.access("/tmp/foo.txt", os.F_OK)
- print ("F_OK - 返回值 %s"% ret)
- ret = os.access("/tmp/foo.txt", os.R_OK)
- print ("R_OK - 返回值 %s"% ret)
- ret = os.access("/tmp/foo.txt", os.W_OK)
- print ("W_OK - 返回值 %s"% ret)
- ret = os.access("/tmp/foo.txt", os.X_OK)
- print ("X_OK - 返回值 %s"% ret)
- #-*-coding:utf-8-*-
- import os,sys
- #假定f1.txt文件存在,并具有读写权限
- file_mode =['os.F_OK','os.R_OK','os.W_OK','os.X_OK']
- #通过序列索引迭代
- for index in range(len(file_mode)):
- results =os.access("f1.txt",eval(file_mode[index]))
- print(str(file_mode[index]) + " - 返回值: %s"% results)
2. 改变当前工作目录
- os.chdir(path) #用于改变当前工作目录到指定的路径
参数:
返回值:如果允许访问返回 True,否则返回 False。
例子:
- #-*-coding:utf-8-*-
- import os,sys
- path = 'D:\\'
- #查看当前工作目录
- print("当前的工作目录为:%s" %os.getcwd())
- #修改当前工作目录
- os.chdir(path)
- #查看修改后的工作目录
- print("目录修改成功 %s" %os.getcwd())
来源: http://www.bubuko.com/infodetail-2000992.html