判断文件夹存在_用Python创建和删除文件夹

用Python创建和删除文件夹,是怎么回事呢?说起文件夹,大家都很熟悉,但是怎么用Python创建和删除文件夹呢?快来和黄叔一起了解一下吧 ~

主要用到os模块,包括:

os.mkdir() # 创建文件夹(已经存在的话会报错)os.makedirs() # 创建多级文件夹(已经存在的话会报错)os.rmdir() # 删除空文件夹(里面有文件的话会报错)

然而,上面也提到一些会报错的情况,所以需要用到其他方法:

os.path.exists() # 判断路径是否存在os.walk() # 输出目录中的文件名os.unlink() # 删除文件

为了让使用更加方便、无脑和快乐,黄叔做了如下的编写:


1. 创建文件夹

def create_dir(path,print_result = False):    import os    existed=os.path.exists(path)    if existed == False:        os.makedirs(path)         message = 'Result: '+path+' created'    else:         message = 'Result: '+path+' already existed'    if print_result:        print(message)

使用示例

path=r"TEMP/temp2"  # 也可以填绝对路径,例如"C:/TEMP/temp2"create_dir(path,print_result=True) # 不填print_result参数,则默认不反馈结果

43943362d9e01d3194a3081d9d5cad40.png

再次执行,也不会报错,仅反馈:

a2cbb0e336236ef7d60ebaf6f4b3b1e1.png


2. 显示文件夹中文件列表

def dir_file_list(path):    file_list = []    import os    for root,dirs,files in os.walk(path):        file_list = file_list+files    return file_list

使用示例

963bf33064010d76f88836f7947822df.png

path="TEMP/temp2"dir_file_list(path)

返回结果是一个list:

['1.txt', '2.txt']

3. 删除文件夹

def remove_dir(path,print_result = False):    import os    existed=os.path.exists(path)    if existed == False:        message = 'Result: '+path+' not existed'    else:        file_list = dir_file_list(path)        file_count = len(file_list)        for file_name in file_list:            os.unlink(path+'/'+file_name)        os.rmdir(path)        message = 'Result: '+path+' already removed with ' + str(file_count) + ' files in it'    if print_result:        print(message)

使用示例

path = r"TEMP\temp2"remove_dir(path,print_result=True)

53ffec632e5b48e43764907f00d6035f.png


本期内容结束了,我们下期不见不散啦。

daf5ab33073161cda285476d1f7b8f82.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值