用Python目录创建及应用


Python目录是计算机语言常用的语言,可是很多人还是对其不太了解,觉得它的实际应用语言操作太难,其实如果你了解了Python目录的操作技能,你对其就有个更深的了解。你如果感兴趣的话,就看看下面的文章吧!

和普通文件一样,关于Python目录的操作也很容易掌握。首先,列出一个目录的内容:

  1. view plaincopy to clipboardprint?  
  2. import os   
  3. for fileName in os.listdir ( '/' ):   
  4. print fileName   
  5. import os  
  6. for fileName in os.listdir ( '/' ):  
  7.  

print fileName正如你所见,这很简单,用三行代码就可以完成。
创建目录也很简单:

  1. view plaincopy to clipboardprint?  
  2. import os   
  3. for fileName in os.listdir ( '/' ):   
  4. print fileName   
  5. import os  
  6. for fileName in os.listdir ( '/' ):  
  7.  

删除刚才创建的Python目录:也可以创建多级目录:

  1. view plaincopy to clipboardprint?  
  2. import os   
  3. os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )   
  4. import os  
  5. os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )  

如果没有在创建的文件夹中添加任何东西,就可以一次性将它们全部删除即,删除所列的所有空文件夹):

  1. view plaincopy to clipboardprint?  
  2. import os   
  3. os.removedirs( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )   
  4. import os  
  5. os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )  

当需要对一个特定的文件类型进行操作时,我们可以选择“fnmatch”模块。以下是显示“.txt”文件的内容和“.exe”文件的文件名:

  1. view plaincopy to clipboardprint?  
  2. import fnmatch   
  3. import os   
  4. for fileName in os.listdir ( '/' ):   
  5. if fnmatch.fnmath ( fileName, '*.txt' ):   
  6. print open ( fileName ).read()   
  7. elif fnmatch.fnmatch ( fileName, '*.exe' ):   
  8. print fileName   
  9. import fnmatch  
  10. import os  
  11. for fileName in os.listdir ( '/' ):  
  12. if fnmatch.fnmath ( fileName, '*.txt' ):  
  13. print open ( fileName ).read()  
  14. elif fnmatch.fnmatch ( fileName, '*.exe' ):  
  15. print fileName“*”  

字符可以表示任意长度的字符。如果要匹配一个字符,则使用“?”符号:

  1. view plaincopy to clipboardprint?  
  2. import fnmatch   
  3. import os   
  4. for fileName in os.listdir ( '/' ):   
  5. if fnmatch.fnmatch ( fileName, '?.txt' ):   
  6. print 'Text file.'   
  7. import fnmatch  
  8. import os  
  9. for fileName in os.listdir ( '/' ):  
  10. if fnmatch.fnmatch ( fileName, '?.txt' ):  
  11. print 'Text file.'“fnmatch”  

以上就是对关于Python目录具体操作内容的简介。

评论关闭