python创建和删除目录的方法

yipeiwu_com6年前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程序设计有所帮助。

相关文章

在VS2017中用C#调用python脚本的实现

情景是这样的:在C#中调用python脚本进行post请求,python脚本中使用了requests包。 Python的开发环境我们有比较多的选择,pycharm、sublime tex...

Python嵌套式数据结构实例浅析

本文实例讲述了Python嵌套式数据结构。分享给大家供大家参考,具体如下: 嵌套式数据结构指的是:字典存储在列表中, 或者列表作为值存储在字典中。甚至还可以在字典中嵌套字典。 1 字典列...

python+opencv实现车牌定位功能(实例代码)

python+opencv实现车牌定位功能(实例代码)

写在前面 HIT大三上学期视听觉信号处理课程中视觉部分的实验三,经过和学长们实验的对比发现每一级实验要求都不一样,因此这里标明了是2019年秋季学期的视觉实验三。 由于时间紧张,代码没有...

Python作用域用法实例详解

本文实例分析了Python作用域用法。分享给大家供大家参考,具体如下: 每一个编程语言都有变量的作用域的概念,Python也不例外,以下是Python作用域的代码演示: def sc...

Python 中的参数传递、返回值、浅拷贝、深拷贝

1. Python 的参数传递 Python的参数传递,无法控制引用传递还是值传递。对于不可变对象(数字、字符、元组等)的参数,更类似值传递;对于可变对象(列表、字典等),更类似引用传递...