python创建和删除目录的方法

yipeiwu_com5年前Python基础

本文实例讲述了python创建和删除目录的方法。分享给大家供大家参考。具体分析如下:

下面的代码可以先创建一个目录,然后调用自定义的deleteDir函数删除整个目录

#--------------------------------------
#      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" );

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Django框架反向解析操作详解

Django框架反向解析操作详解

本文实例讲述了Django框架反向解析操作。分享给大家供大家参考,具体如下: 1. 定义: 随着功能的增加会出现更多的视图,可能之前配置的正则表达式不够准确,于是就要修改正则表达式,但是...

Python教程之全局变量用法

本文实例讲述了Python全局变量用法。分享给大家供大家参考,具体如下: 全局变量不符合参数传递的精神,所以,平时我很少使用,除非定义常量。今天有同事问一个关于全局变量的问题,才发现其中...

在OpenCV里实现条码区域识别的方法示例

在OpenCV里实现条码区域识别的方法示例

在我们识别条码的过程里,首先要找到条码所在的区域,那么怎么样来找到这个条码的区域呢?如果仔细地观察条码,会发现条码有一个特性,就是水平的梯度和垂值的梯度会不一样,如果进行相减,会发现差值...

Python中三元表达式的几种写法介绍

要介绍Python的三元表达式,可以先看看其他编程语言比如C,JAVA中应用: public class java { public static void main(String...

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...