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

相关文章

python3.7 利用函数os pandas利用excel对文件名进行归类

python3.7 利用函数os pandas利用excel对文件名进行归类

这里用的python 版本是3.7最新的版本写的。 利用excel ,对门店的二维码对对应所属小区进行分类,比如在excel 江南摩尔店对应浙北大区,那么二维码名字为...

Numpy之文件存取的示例代码

上一篇中我们简要带过了Numpy的数据持久化,在这一篇中将要具体说明Numpy提供的文件存取功能。Numpy可以将数组保存至二进制文件、文本文件,同时支持将多个数组保存至一个文件中。 1...

python使用tomorrow实现多线程的例子

python使用tomorrow实现多线程的例子

如下所示: import time,requestes from tomorrow import threads @threads(10)#使用装饰器,这个函数异步执行 def d...

Python使用指定端口进行http请求的例子

使用requests库 class SourcePortAdapter(HTTPAdapter): """"Transport adapter" that allows us to...

Python内置模块turtle绘图详解

Python内置模块turtle绘图详解

urtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x、纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,...