[Python] python创建和删除目录的代码 →→→→→进入此内容的聊天室

来自 , 2021-02-21, 写在 Python, 查看 107 次.
URL http://www.code666.cn/view/070c425f
  1. #------------------------------------------------------------------------------
  2. #           Name: create_directory.py
  3. #         Author: Kevin Harris
  4. #  Last Modified: 02/13/04
  5. #    Description: This Python script demonstrates how to create a single
  6. #                 new directory as well as delete a directory and everything
  7. #                 it contains. The script will fail if encountewrs a read-only
  8. #                 file
  9. #------------------------------------------------------------------------------
  10.  
  11. import os
  12.  
  13. #------------------------------------------------------------------------------
  14. # Name: deleteDir()
  15. # Desc: Deletes a directory and its content recursively.
  16. #------------------------------------------------------------------------------
  17. def deleteDir( dir ):
  18.    
  19.     for name in os.listdir( dir ):
  20.        
  21.         file = dir + "/" + name
  22.        
  23.         if not os.path.isfile( file ) and os.path.isdir( file ):
  24.             deleteDir( file ) # It's another directory - recurse in to it...
  25.         else:
  26.             os.remove( file ) # It's a file - remove it...
  27.            
  28.     os.rmdir( dir )
  29.  
  30. #------------------------------------------------------------------------------
  31. # Script entry point...
  32. #------------------------------------------------------------------------------
  33.  
  34. # Creating a new directory is easy...
  35.  
  36. os.mkdir( "test_dir" )
  37.  
  38. # Pause for a moment so we can actually see the directory get created.
  39. input( 'A directory called "tes_dir" was created.\n\nPress Enter to delete it.' )
  40.  
  41. # Deleting it can be a little harder since it may contain files, so we'll need
  42. # to write a function to help us out here.
  43.  
  44. deleteDir( "test_dir" );
  45.  
  46. #//python/8090

回复 "python创建和删除目录的代码"

这儿你可以回复上面这条便签

captcha