python delete all files in the folder

python delete all files in the folder


If you want to delete a particular file, use the following method:
import os
#删除特定的文件
def del_avatar(path):
    if os.path.exists(path):  # 如果文件存在
        os.remove(path)  
    else:
        print('no such file:%s'%(path))  # 则返回文件不存在

What if you want to delete all files under a file?

import os
#删除一个文件夹下的所有所有文件
def del_file(path):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):#如果是文件夹那么递归调用一下
            del_file(c_path)
        else:                    #如果是一个文件那么直接删除
            os.remove(c_path)
    print ('文件已经清空完成')

Guess you like

Origin blog.csdn.net/weixin_45386875/article/details/113818462