python 删除顽固文件的处理办法(How to delete stubborn files in Python)

记录一个之前遇到的事情. 

有的时候安装了一个程序后, 没有卸载入口. 进程杀了后, 过不了多久还会自己启动. 文件非常难删除. 基本上都是在和电脑拼手速.

你知道它的安装位置和文件 ,但你就是很难搞死它. 我知道你也遇到过对不对? 

照例先搬运相关知识点:

今天要用到 os 和 sys 模块

os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。

使用参考: https://www.runoob.com/python/os-walk.html

os.popen() 方法用于从一个命令打开一个管道。

使用参考: https://www.runoob.com/python/os-popen.html

os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。

使用参考: https://www.runoob.com/python/os-remove.html

os.removedirs() 方法用于递归删除目录。像rmdir(), 如果子文件夹成功删除, removedirs()才尝试它们的父文件夹,直到抛出一个error(它基本上被忽略,因为它一般意味着你文件夹不为空)。

使用参考: https://www.runoob.com/python/os-removedirs.html

os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。

使用参考:  https://www.runoob.com/python/os-rmdir.html

sys.argv[]

说白了就是一个从程序外部获取参数的桥梁。

因为我们从外部取得的参数可以是多个,所以获得的是一个列表(list),也就是说sys.argv其实可以看作是一个列表,所以才能用[]提取其中的元素。

其第一个元素是程序本身,随后才依次是外部给予的参数。

import sys
a=sys.argv[0]
print(a)

import sys
a=sys.argv[0]
print(a)

可以自己试试看输入的是不是你当前运行路径

实现思路: 获取当前路径–>获取路径下所有文件–>找到exe文件–>关闭exe文件(自身除外)–>删除所有文件–>删除文件夹–>结束

源码如下:

import os
import time
import logging
import sys


def set_log(log_name):
    # 设置log格式
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    logging.basicConfig(filename=log_name, level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)


def get_file_dict(_path):
"""获取所有文件列表"""
    files_dict = {}
    for root, dirs, files in os.walk(_path):  # 获取该文件夹下所有文件
        logging.debug("获取文件夹下所有文件 get_file_dict({}):{}{}{}".format(local_path, root, dirs, files))
        for file in files:
            files_dict[file] = root
    logging.debug("return path_dict:{}".format(files_dict))
    return files_dict


def kill_exe(name_exe):
    cmd = 'taskkill /f /im ' + '\"' + name_exe + '\"'  # 关闭进程命令
    os.popen(cmd)  # popen()执行速度快,无显    # os.system(cmd)  # 多一个显示,执行速度慢
    logging.debug("kill_exe({}):{}".format(name_exe, cmd))


def del_file(path_dict, run_exe):
for key in path_dict:
        if str(key) == str(run_exe) or key == 'log.log':
            pass
        else:
            _path = path_dict[key] + '\\' + key
            try:
                os.remove(_path)
                logging.info("DELETE FILE SUCCESS {}".format(_path))
            except Exception as e:
                logging.error("os.remove({}):{}".format(_path, e))


def del_dir(_path):
""" 删除文件夹 """
    for root, dirs, files in os.walk(_path):
        if dirs == [] and files == []:
            try:
                os.rmdir(root)
                logging.info("DELETE DIR SUCCESS {}".format(root))

            except Exception as e:
                logging.error("os.rmdir({}):{}".format(root, e))


def close_all_exe(path_dict, run_exe):
for key in path_dict:
        if str(key) == str(run_exe):
            continue
        if key.endswith('exe'):
       logging.debug("kill_exe:".format(key))


if __name__ == '__main__':
    set_log("del.log")

    local_path = sys.argv[0]  # 获取运行路径
    # 当前运行程序名字
    del_exe = ''
    if '\\' in local_path:
        del_exe = local_path.split("\\")[-1]
        logging.debug(f"del_exe:{del_exe}")

    if '/' in local_path:
        del_exe = local_path.split("/")[-1]
        logging.debug(f"del_exe:{del_exe}")

    path = os.getcwd()  # 获取当前文件夹路径
    path_dict = get_file_dict(path)  
    logging.INFO("开始执行...")
    while True:                              # 在实际操作调试中,发现对方程序异常顽强,故用了死循环,手动关闭程序结束流程
        # 关闭exe进程
        close_all_exe(path_dict, del_exe)
        time.sleep(5)
        # 获取其他文件 删除
        del_file(path_dict, del_exe)
        # 删除空文件夹s
        del_dir(local_path)
————————

Record a previous encounter

Sometimes there is no uninstall entry after installing a program After the process is killed, it will start itself soon The file is very difficult to delete Basically, they are fighting hand speed with computers

You know its installation location and files, but it’s hard for you to kill it I know you’ve met, haven’t you?

Carry relevant knowledge points first as usual:

< strong > OS and sys modules will be used today < / strong >

os. The walk () method is a simple and easy-to-use file and directory traverser, which can help us deal with files and directories efficiently.

使用参考: https://www.runoob.com/python/os-walk.html

os. The Popen () method is used to open a pipe from a command.

使用参考: https://www.runoob.com/python/os-popen.html

os. The remove () method is used to delete the file in the specified path. If the specified path is a directory, an oserror is thrown.

使用参考: https://www.runoob.com/python/os-remove.html

os. The removediers () method is used to recursively delete directories. Like rmdir (), if the subfolders are successfully deleted, removediers () tries their parent folder until an error is thrown (it is basically ignored because it generally means that your folder is not empty).

使用参考: https://www.runoob.com/python/os-removedirs.html

os. The rmdir() method is used to delete the directory of the specified path. Only when the folder is empty, otherwise, an oserror is thrown.

使用参考:  https://www.runoob.com/python/os-rmdir.html

sys.argv[]

To put it bluntly, it is a bridge to obtain parameters from outside the program.

Because we can get multiple parameters from the outside, we get a list, that is, sys Argv can actually be regarded as a list, so [] can be used to extract the elements in it.

The first element is the program itself, followed by externally given parameters.

import sys
a=sys.argv[0]
print(a)

import sys
a=sys.argv[0]
print(a)

You can try to see if the input is your current running path

Implementation idea: get the current path — & gt; Get all files under the path — & gt; Exe file found — & gt; Close EXE file (except itself) – & gt; Delete all files — & gt; Delete folder — & gt; end

The source code is as follows:

import os
import time
import logging
import sys


def set_log(log_name):
    # 设置log格式
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    logging.basicConfig(filename=log_name, level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)


def get_file_dict(_path):
"""获取所有文件列表"""
    files_dict = {}
    for root, dirs, files in os.walk(_path):  # 获取该文件夹下所有文件
        logging.debug("获取文件夹下所有文件 get_file_dict({}):{}{}{}".format(local_path, root, dirs, files))
        for file in files:
            files_dict[file] = root
    logging.debug("return path_dict:{}".format(files_dict))
    return files_dict


def kill_exe(name_exe):
    cmd = 'taskkill /f /im ' + '\"' + name_exe + '\"'  # 关闭进程命令
    os.popen(cmd)  # popen()执行速度快,无显    # os.system(cmd)  # 多一个显示,执行速度慢
    logging.debug("kill_exe({}):{}".format(name_exe, cmd))


def del_file(path_dict, run_exe):
for key in path_dict:
        if str(key) == str(run_exe) or key == 'log.log':
            pass
        else:
            _path = path_dict[key] + '\\' + key
            try:
                os.remove(_path)
                logging.info("DELETE FILE SUCCESS {}".format(_path))
            except Exception as e:
                logging.error("os.remove({}):{}".format(_path, e))


def del_dir(_path):
""" 删除文件夹 """
    for root, dirs, files in os.walk(_path):
        if dirs == [] and files == []:
            try:
                os.rmdir(root)
                logging.info("DELETE DIR SUCCESS {}".format(root))

            except Exception as e:
                logging.error("os.rmdir({}):{}".format(root, e))


def close_all_exe(path_dict, run_exe):
for key in path_dict:
        if str(key) == str(run_exe):
            continue
        if key.endswith('exe'):
       logging.debug("kill_exe:".format(key))


if __name__ == '__main__':
    set_log("del.log")

    local_path = sys.argv[0]  # 获取运行路径
    # 当前运行程序名字
    del_exe = ''
    if '\\' in local_path:
        del_exe = local_path.split("\\")[-1]
        logging.debug(f"del_exe:{del_exe}")

    if '/' in local_path:
        del_exe = local_path.split("/")[-1]
        logging.debug(f"del_exe:{del_exe}")

    path = os.getcwd()  # 获取当前文件夹路径
    path_dict = get_file_dict(path)  
    logging.INFO("开始执行...")
    while True:                              # 在实际操作调试中,发现对方程序异常顽强,故用了死循环,手动关闭程序结束流程
        # 关闭exe进程
        close_all_exe(path_dict, del_exe)
        time.sleep(5)
        # 获取其他文件 删除
        del_file(path_dict, del_exe)
        # 删除空文件夹s
        del_dir(local_path)