欢迎访问宙启技术站
智能推送

如何在Python中使用win32com.shell.shell执行文件操作

发布时间:2024-01-14 10:38:58

在Python中使用win32com.shell.shell模块可以执行一些Windows文件操作,如创建文件夹、复制文件、删除文件等。下面是使用例子,包括创建文件夹、复制文件和删除文件。

首先,需要安装pywin32库,可以使用以下命令来安装:

pip install pywin32

接下来,可以使用下面的代码来进行文件操作:

import os
import win32com.shell.shell as shell

# 创建文件夹
def create_folder(path):
    if not os.path.exists(path):
        shell.SHCreateDirectoryEx(None, path, None)
        print(f"文件夹 {path} 创建成功")
    else:
        print(f"文件夹 {path} 已存在")

# 复制文件
def copy_file(source, destination):
    if os.path.exists(source):
        shell.SHFileOperation((
            0,
            shellcon.FO_COPY,
            source,
            destination,
            shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION,
            None,
            None
        ))
        print(f"文件 {source} 复制到 {destination} 成功")
    else:
        print(f"文件 {source} 不存在")

# 删除文件
def delete_file(path):
    if os.path.exists(path):
        shell.SHFileOperation((
            0,
            shellcon.FO_DELETE,
            path,
            None,
            shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION,
            None,
            None
        ))
        print(f"文件 {path} 删除成功")
    else:
        print(f"文件 {path} 不存在")

上述代码定义了三个函数:create_foldercopy_filedelete_file。这些函数使用win32com.shell.shell模块的API来执行文件操作。

create_folder函数用于创建文件夹。如果文件夹不存在,则调用shell.SHCreateDirectoryEx函数创建文件夹。函数接受一个参数path,代表要创建的文件夹路径。

copy_file函数用于复制文件。如果源文件存在,则调用shell.SHFileOperation函数执行文件复制操作。函数接受两个参数sourcedestination,分别代表源文件路径和目标文件路径。

delete_file函数用于删除文件。如果文件存在,则调用shell.SHFileOperation函数执行文件删除操作。函数接受一个参数path,代表要删除的文件路径。

下面是使用这些函数的示例代码:

# 创建文件夹
create_folder("C:\\Test")

# 复制文件
copy_file("C:\\Test\\file.txt", "C:\\Test\\file_copy.txt")

# 删除文件
delete_file("C:\\Test\\file_copy.txt")

运行上述代码,将在C:\Test目录下创建一个文件夹,然后将C:\Test\file.txt文件复制到C:\Test\file_copy.txt,最后删除C:\Test\file_copy.txt文件。

总结:win32com.shell.shell模块提供了一些方便的API,可以在Python中执行一些Windows文件操作。上述代码演示了如何使用该模块来创建文件夹、复制文件和删除文件。