Python删除目录下的所有文件

版权声明:小妖666个人笔记 https://blog.csdn.net/weixin_38883338/article/details/86644472

代码:

#!/usr/bin/python
import os
datapath=r'/home/data/'
resultpath=r'/home/result'
realpath=os.path.realpath(__file__)
def del_file(path,realpath):
    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,realpath)
        elif c_path <> realpath:
            os.remove(c_path)
print c_path
del_file(datapath,realpath)
del_file(resultpath,realpath)

解释:

获取执行文件绝对路径:os.path.realpath(__file__)

以数组形式获取路径下的文件以及文件夹:os.listdir(path)

判断是否是文件夹:os.path.isdir          若是文件夹,继续执行查找文件函数del_file

删除文件:os.remove(c_path)

猜你喜欢

转载自blog.csdn.net/weixin_38883338/article/details/86644472