Python methods for creating and deleting directories

Source: Internet
Author: User
The examples in this article describe how Python creates and deletes directories. Share to everyone for your reference. The specific analysis is as follows:

The following code creates a directory and then invokes the custom Deletedir function to delete the entire directory

#--------------------------------------# 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 would 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 O    S.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 ' Te S_dir "was created.\n\npress Enter to delete it. ') # Deleting It can be a little harder since it could contain files, so we'll need # to write a function to help us out HERE.D Eletedir ("Test_dir");

Hopefully this article will help you with Python programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.