使用python中的Win32 api

使用python中的Win32 api,python,winapi,Python,Winapi,activestate python帮助文件中提供了以下代码。此代码用于递归删除文件夹中的文件,然后删除文件夹本身。请指出其中的错误,因为我想使用python使用win32 api import win32con import win32api import os def del_dir(path): for file_or_dir in os.listdir(path): if os.path.isdir(file_or_dir) and not os.path.is

activestate python帮助文件中提供了以下代码。此代码用于递归删除文件夹中的文件,然后删除文件夹本身。请指出其中的错误,因为我想使用python使用win32 api

import win32con
import win32api
import os

def del_dir(path):
    for file_or_dir in os.listdir(path):
        if os.path.isdir(file_or_dir) and not os.path.islink(file_or_dir):
            del_dir(file_or_dir) #recursive call to function again
        else:
            try:
                os.remove(file_or_dir) #it's a file,delete is
            except:
                #probably failed because it is not a normal file
                win32api.SetFileAttributes(file_or_dir,win32con.FILE_ATTRIBUTE_NORMAL)
                os.remove(file_or_dir) #it's a file delete it

        os.rmdir(path)#delete the directory here

程序的问题与win32api无关。它失败是因为无论何时调用任何OS函数(OS.remove、win32api.SetFileAttributes),都只传递部分名称(即“path”后面的部分)。 将函数的第一行更改为:

def del_dir(path):
    for file_or_dir in os.listdir(path):
改为:

def del_dir(path):
    for x in os.listdir(path):
        file_or_dir = os.path.join(path,x)
其余的都是一样的。顺便说一句,删除整个目录或递归遍历文件夹层次结构,这确实是一个糟糕的示例。使用os.walk获得简单代码

一般来说,win32api和win32con工作正常。打开python外壳并尝试以下更简单的代码:

>>> import win32api
>>> import win32con
>>> win32api.MessageBox(0, "hello win32api", "win32api", win32con.MB_OK)

要删除整个目录树,可以改用
shutil.rmtree
。请参阅。如果存在
shutil.rmtree
,则不知道为什么会存在此代码。