如何使用Python实现USB闪存驱动器格式化功能?
使用Python格式化USB驱动器的实现方法
格式化USB属于高危操作,必须精准确认目标设备路径/盘符,避免误格式化系统盘或其他重要存储设备。Python本身没有跨平台的格式化API,通常通过调用系统自带的磁盘工具实现,以下分平台说明:
Windows平台实现
Windows下可通过调用diskpart工具完成格式化,需要以管理员身份运行脚本:
示例函数
import subprocess def format_usb_windows(drive_letter: str, filesystem: str = "NTFS", quick_format: bool = True): # 构造diskpart脚本内容 script = f""" select volume {drive_letter} format fs={filesystem.lower()} {'quick' if quick_format else ''} exit """.strip() try: # 执行diskpart命令,传入脚本 result = subprocess.run( ["diskpart", "/s", "-"], input=script.encode("utf-8"), check=True, capture_output=True, text=True ) print(f"格式化完成:{result.stdout}") except subprocess.CalledProcessError as e: print(f"格式化失败:{e.stderr}")
使用说明
drive_letter:USB驱动器的盘符,比如D:filesystem:可选文件系统,支持NTFS、FAT32、exFAT- 运行前必须确认盘符正确,且USB未被占用
Linux/macOS平台实现
Linux和macOS下通过调用mkfs系列命令完成,需要root权限(执行时输入sudo密码或配置免密sudo):
示例函数
import subprocess def format_usb_unix(device_path: str, filesystem: str = "ntfs", quick_format: bool = True): # 构造mkfs命令参数 cmd = ["sudo", f"mkfs.{filesystem}"] if quick_format: cmd.append("-F") # 快速格式化参数,不同文件系统可能略有差异,比如ext4用-F,fat32用-v等 cmd.append(device_path) try: # 执行命令,需要输入sudo密码的话会在终端提示 result = subprocess.run(cmd, check=True, capture_output=True, text=True) print(f"格式化完成:{result.stdout}") except subprocess.CalledProcessError as e: print(f"格式化失败:{e.stderr}")
使用说明
device_path:USB设备的挂载路径,比如Linux的/dev/sdb1,macOS的/dev/disk2s1filesystem:可选文件系统,Linux支持ntfs(需安装ntfs-3g)、ext4、fat32;macOS支持msdos(对应FAT32)、ntfs(需第三方工具)、exfat- 可通过
lsblk(Linux)或diskutil list(macOS)命令查看设备路径
跨平台封装(可选)
可以通过platform模块判断操作系统,封装成统一函数:
import platform def format_usb(target: str, filesystem: str = "NTFS", quick_format: bool = True): os_type = platform.system() if os_type == "Windows": format_usb_windows(target, filesystem, quick_format) elif os_type in ["Linux", "Darwin"]: format_usb_unix(target, filesystem.lower(), quick_format) else: print(f"不支持的操作系统:{os_type}")
关键注意事项
- 权限要求:Windows需管理员权限,Linux/macOS需root权限
- 设备识别:必须通过系统命令确认目标设备,绝对不能凭猜测填写路径/盘符
- 数据备份:格式化前务必备份USB内的所有数据,一旦执行无法恢复
- 文件系统兼容性:根据使用场景选择合适的文件系统,比如跨平台用
exFAT,Windows用NTFS,老旧设备用FAT32
内容的提问来源于stack exchange,提问作者Canofeggs 5410
相关产品推荐
相关产品推荐

