当前位置:   article > 正文

python os模块的学习

python os模块的学习

python的标准库有很多,还有第三方库,多的都学不过来了,千里之行始于足下,每周学两到三个模块,慢慢的就掌握的多了,学习的过程中做一下笔记,或许能给想学习相关模块的人以一些帮助......

1、遍历文件夹(os.walk)
   
   文件夹(C:\Users\Desktop\Python)描述:
       该文件夹下包含一个文件夹(标准库)和一个文件(Python核心编程(第二版).pdf)
       文件夹(标准库)下包含一个文件(51CTO下载-python标准库.pdf)
   代码:
 

  1. import os
  2. directory = "C:\Users\Desktop\Python"
  3. for parent,dirnames,filenames in os.walk(directory):
  4. print parent
  5. for dirname in dirnames:
  6. print dirname
  7. print os.path.join(parent,dirname)
  8. for filename in filenames:
  9. print filename
  10. print os.path.join(parent,filename)


    程序说明:
       os.walk将目录一级一级的遍历,程序中的parent,dirnames,filenames分别指的是父级目录,文件夹,文件
       第一次遍历,父级目录为C:\Users\Desktop\Python,文件夹为 标准库,文件名为Python核心编程(第二版).pdf
          故输出结果:
            
  1. C:\Users\Desktop\Python
  2. 标准库
  3. C:\Users\Desktop\Python\标准库
  4. Python核心编程(第二版).pdf
  5. C:\Users\Desktop\Python\Python核心编程(第二版).pdf



       第二次遍历,父级目录为C:\Users\Desktop\Python\标准库,文件夹为空,文件名为51CTO下载-python标准库.pdf
          故输出结果:
           
  1. C:\Users\Desktop\Python\标准库
  2. 51CTO下载-python标准库.pdf
  3. C:\Users\Desktop\Python\标准库\51CTO下载-python标准库.pdf


       程序结束
2、获取当前目录
     os.getcwd()
3、创建与删除目录(makedirs,mkdir,removedirs,rmdir)
   mkdir与makedirs
       makedirs当中间目录没有的情况下回自动创建以保证所要的目录能够创建完成
       比如:在目录D:\资料下创建D:\资料\python\linux,尽管没有目录D:\资料\python还是会创建成功
             而mkdir就不会创建,报错
   rmdir与removedirs
       首先说明:
          这两个函数只能删除空文件夹(注意是空的,并且是文件夹)
       rmdir只能删除最后一级的空文件夹
       remove删除所有空的文件夹
4、os.path
   代码:
 
  1. import os
  2. directory = "C:\Users\Desktop\Python"
  3. for parent,dirnames,filenames in os.walk(directory):
  4. file1 = parent
  5. for dirname in dirnames:
  6. file2 = os.path.join(parent,dirname)
  7. for filename in filenames:
  8. file3 = os.path.join(parent,filename)
  9. files = []
  10. files.extend([file1,file2,file3])
  11. for File in files:
  12. print File,"-->",
  13. if os.path.isabs(File):
  14. print "isabs",
  15. if os.path.isdir(File):
  16. print "isdir",
  17. if os.path.isfile(File):
  18. print "isfile",
  19. if os.path.exists(File):
  20. print "exists"
  21. break


   结果:
  
  1. C:\Users\Desktop\Python --> isabs isdir exists
  2. C:\Users\Python\标准库 --> isabs isdir exists
  3. C:\Users\Desktop\Python\Python核心编程(第二版).pdf --> isabs isfile exists


5、os执行操作系统的命令
   代码:
       import os
       os.system("ls")
   结果:

  

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/838559
推荐阅读
相关标签
  

闽ICP备14008679号