python 文件目录操作

来源:互联网 发布:骚男的辣条淘宝店网址 编辑:程序博客网 时间:2024/04/30 17:45

os和os.path模块

os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回但前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径

view plainprint?
  1. >>> import os  
  2. >>> os.getcwd()  
  3. 'C:\\Python25'  
  4. >>> os.chdir(r'C:\temp')  
  5. >>> os.getcwd()  
  6. 'C:\\temp'  
  7. >>> os.listdir('.')  
  8. ['temp.txt', 'test.py', 'testdir', 'tt']  
  9. >>> os.listdir(os.curdir)  
  10. ['temp.txt', 'test.py', 'testdir', 'tt']  
  11. >>> os.path.getsize('test.py')  
  12. 38L  
  13. >>> os.path.isdir('tt')  
  14. True  
  15. >>> os.path.getsize('tt')  
  16. 0L  
  17. >>> os.path.abspath('tt')  
  18. 'c:\\temp\\tt'  
  19. >>> os.path.abspath('test.py')  
  20. 'c:\\temp\\test.py'  
  21. >>> os.path.abspath('.')  
  22. 'c:\\temp'  
  23. >>>  
  24. >>> os.path.split(r'.\tt')  
  25. ('.', 'tt')  
  26. >>> os.path.split(r'c:\temp\test.py')  
  27. ('c:\\temp', 'test.py')  
  28. >>> os.path.split(r'c:\temp\test.dpy')  
  29. ('c:\\temp', 'test.dpy'  
  30.   
  31. >>> os.path.splitext(r'c:\temp\test.py')  
  32. ('c:\\temp\\test', '.py')  
  33. >>> os.path.splitext(r'c:\temp\tst.py')  
  34. ('c:\\temp\\tst', '.py')  
  35. >>>  
  36. >>> os.path.basename(r'c:\temp\tst.py')  
  37. 'tst.py'  
  38. >>> os.path.dirname(r'c:\temp\tst.py')  
  39. 'c:\\temp'  
  40. >>>  

 os.sep 可以取代操作系统特定的路径分割符。

os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

os.getenv()和os.putenv()函数分别用来读取和设置环境变量。

os.remove()函数用来删除一个文件。

os.system()函数用来运行shell命令。

os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'/r/n',Linux使用'/n'而Mac使用'/r'。

os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

os.curdir:返回但前目录('.')可使用abspath来获取绝对路劲

>>>dir = glob.glob('*.dat')  #获取当前目录的dat文件列表

.创建目录
os.mkdir(path)    path:要创建目录的路径。

>>> import os
>>> os.mkdir('E:\\book\\temp')   # 使用os.mkdir创建目录

4.删除目录
os.rmdir(path)   path:要删除的目录的路径。

>>> import os
>>> os.rmdir('E:\\book\\temp')   # 删除目录

需要说明的是,使用os.rmdir删除的目录必须为空目录,否则函数出错。

若想删除非空目录,先删除目录下的文件,然后再删除目录,递归过程。