day5-os

os模块

1. os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径

1 >>> os.getcwd()
2 'D:\\Python27\\Python27'

2. os.chdir(文件目录)  #改变当前脚本工作目录;相当于shell下cd

1 >>> os.chdir('D:\\Python27\\')
2 >>> os.getcwd()
3 'D:\\Python27'

3. os.curdir  #返回当前目录,即'.' 

    os.pardir  #获取当前目录的父目录字符串名,即'..'

4. os.mkdir('dirname')    #生成单级目录;相当于shell中mkdir dirname

    os.makedirs('dirname1/dirname2')    #可生成多层递归目录

    os.remove()  #删除一个文件

    os.rmdir('dirname')    #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

    os.removedirs('dirname1')    #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

5. os.listdir(文件目录)    #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

1 >>> os.listdir('D:\\Python27\\Python27')
2 ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools', 'w9xpopen.exe']

6. os.rename("oldname","newname")  #重命名文件或者目录

7. os.stat('path/filename')  #获取文件或者目录信息

8. os.sep    #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"

    os.linesep    #输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"

    os.pathsep    #输出用于分割文件路径的字符串

9. os.name    #输出字符串指示当前使用平台,win->'nt'; Linux->'posix'

10. os.environ  #获取系统环境变量

11. os.system("bash command")  #运行shell命令,直接显示,不保存结果

      os.popen(cmd).read() #执行命令,输出结果

12. os.path.abspath(path)  #返回path的绝对路径

1 >>> path = 'D:\\Python27\\Python27\\README.txt'
2 >>> os.path.abspath(path)
3 'D:\\Python27\\Python27\\README.txt'

13. os.path.split(path)  #返回path的(目录,文件名)元组

1 >>> os.path.split(path)
2 ('D:\\Python27\\Python27', 'README.txt')

14. os.path.dirname(path)  #返回path的目录

1 >>> os.path.dirname(path)
2 'D:\\Python27\\Python27'

15. os.path.basename(path)  #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值

1 >>> os.path.basename(path)
2 'README.txt'

16. os.path.exists(path)  #如果path存在,返回True;如果path不存在,返回False

1 >>> os.path.exists(path)
2 True

17. os.path.isabs(path) #如果path是绝对路径,返回True

1 >>> os.path.isabs(path)
2 True

18. os.path.isfile(path)  #如果path是一个存在的文件,返回True。否则返回False

1 >>> os.path.isfile(path)
2 True

19. os.path.isdir(path)  #如果path是一个存在的目录,则返回True。否则返回False

1 >>> os.path.isdir(path)
2 False

20. os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

1 >>> os.path.join('D:\\Python27\\Python27','README.txt')
2 'D:\\Python27\\Python27\\README.txt'

21. os.path.getatime(path)  #返回path所指向的文件或者目录的最后存取时间戳

22. os.path.getmtime(path)  #返回path所指向的文件或者目录的最后修改时间戳

23. os.walk() 方法用于通过在目录树中游走输出目录中的文件名,向上或者向下,在Unix,Windows中有效

1 import os
2 for root, dirs, files in os.walk(".", topdown=False):
3     for name in files:
4         print(os.path.join(root, name))
5     for name in dirs:
6         print(os.path.join(root, name))

 

posted @ 2017-06-17 20:38  不知所以  阅读(103)  评论(0)    收藏  举报