自用函数(持续更新)

 防止win32com结束后有excel进程残留

import win32com.client
import win32process,win32api,win32con
excel = win32com.client.DispatchEx('Excel.Application')
def close_excel_by_force(excel):  # 关闭进程

        # Get the window's process id's
        hwnd = excel.Hwnd
        #hwnd = win32gui.FindWindowEx(0,0,None,name)
        t, p = win32process.GetWindowThreadProcessId(hwnd)
        # Ask window nicely to close
        try:
            handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
            if handle:
                win32api.TerminateProcess(handle, 0)
                win32api.CloseHandle(handle)
        except:
            pass

防止shutil删除文件时因文件属性删除失败

import shutil
shutil.rmtree(path,onerror=remove_readonly)
def remove_readonly(func, path, _):  # 错误回调函数,改变只读属性位,重新删除
    #"Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

清空文件夹

import shutil,os
def clearfolder(self,path):
    if os.path.exists(path):
        shutil.rmtree(path,onerror=remove_readonly)
        time.sleep(1)
    os.makedirs(path)

自动分派尾号(可用于分配文件名)

a=['ddd','ddd-1','ddd-2']
b='ddd'
def checkexists(list1,str1,num=0):    #检查是否已存在此文件名,若存在自动指派尾号
    num+=1
    if str1 not in list1:return str1
    str2 = str1+'-'+str(num)
    if str2 in list1:       
        str2 = checkexists(list1,str1,num)
    return str2
checkexists(a,b)

你可能感兴趣的:(小练习,python)