本文實(shí)例講述了python創(chuàng)建和刪除目錄的方法。分享給大家供大家參考。具體分析如下:
下面的代碼可以先創(chuàng)建一個(gè)目錄,然后調(diào)用自定義的deleteDir函數(shù)刪除整個(gè)目錄
#--------------------------------------# Name: create_directory.py# Author: Kevin Harris# Last Modified: 02/13/04# Description: This Python script demonstrates# how to create a single# new directory as well as delete a directory# and everything # it contains. The script will fail # if encountewrs a read-only# file#--------------------------------------import os#--------------------------------------# Name: deleteDir()# Desc: Deletes a directory and its content recursively.#--------------------------------------def deleteDir( dir ): for name in os.listdir( dir ): file = dir + "/" + name if not os.path.isfile( file ) and os.path.isdir( file ): deleteDir( file ) # It's another directory - recurse in to it... else: os.remove( file ) # It's a file - remove it... os.rmdir( dir )#--------------------------------------# Script entry point...#--------------------------------------# Creating a new directory is easy...os.mkdir( "test_dir" )# Pause for a moment so we can actually see the directory get created.input( 'A directory called "tes_dir" was created./n/nPress Enter to delete it.' )# Deleting it can be a little harder since it may contain files, so we'll need # to write a function to help us out here.deleteDir( "test_dir" );
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選