Windows下Python自动识别U盘盘符并写入鱼菜共生日志文件的方法
识别U盘盘符并写入日志文件的Python方案
嘿,针对你鱼菜共生项目里的这个U盘日志写入需求,我有几个实用的Python方案,能帮你自动识别U盘盘符,不用手动改路径~
方案1:用Windows API(无需额外库)
如果你的运行环境不想装额外依赖,直接用Python自带的ctypes调用Windows系统API来枚举可移动磁盘是最稳妥的:
import ctypes import os def get_removable_drives(): drives = [] # 调用Windows API获取逻辑驱动器列表 bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in range(65, 91): # 遍历A-Z所有盘符 drive = chr(letter) + ":\\" if bitmask & (1 << (letter - 65)): # 判断当前驱动器是否为可移动磁盘 drive_type = ctypes.windll.kernel32.GetDriveTypeW(drive) if drive_type == 2: # DRIVE_REMOVABLE 代表可移动磁盘 drives.append(drive) return drives def write_log_to_usb(content, filename="aquaponics_log.txt"): usb_drives = get_removable_drives() if not usb_drives: print("未检测到可移动磁盘!") return # 如果插入多个U盘,这里可以加逻辑筛选(比如按卷标匹配) usb_path = usb_drives[0] log_path = os.path.join(usb_path, filename) try: with open(log_path, "a", encoding="utf-8") as f: f.write(content + "\n") print(f"日志已成功写入:{log_path}") except Exception as e: print(f"写入失败:{str(e)}") # 测试调用:写入当前时间和传感器数据示例 if __name__ == "__main__": import datetime log_content = f"{datetime.datetime.now()} - pH值: 6.8, 水温: 25.5°C" write_log_to_usb(log_content)
方案2:用psutil库(代码更简洁)
如果允许安装第三方库,psutil能更直观地获取磁盘信息,代码可读性更高:
首先安装依赖库:
pip install psutil
然后是示例代码(推荐给U盘设置固定卷标来精准识别):
import psutil import os import datetime import ctypes def get_target_usb_drive(target_label="AquaponicsLog"): # 遍历所有磁盘分区 for partition in psutil.disk_partitions(all=True): # 筛选可移动磁盘 if 'removable' in partition.opts and partition.mountpoint: try: # 获取U盘卷标(Windows系统下) buffer = ctypes.create_unicode_buffer(256) ctypes.windll.kernel32.GetVolumeInformationW( partition.mountpoint, buffer, ctypes.sizeof(buffer), None, None, None, None, 0 ) current_label = buffer.value # 匹配目标卷标(提前给你的U盘设置好这个卷标) if current_label == target_label: return partition.mountpoint except: continue return None def write_aquaponics_log(content): usb_path = get_target_usb_drive() if not usb_path: print("找不到目标U盘!请检查U盘是否插入或卷标是否正确") return log_file = os.path.join(usb_path, "aquaponics_log.txt") with open(log_file, "a", encoding="utf-8") as f: f.write(f"{datetime.datetime.now()} - {content}\n") print(f"日志已写入U盘:{log_file}") # 测试:写入传感器数据 write_aquaponics_log("pH值: 6.7, 溶解氧: 5.2mg/L")
实用小提示
- 建议给你的U盘设置固定卷标(右键U盘→属性→常规栏修改),这样代码可以精准定位目标U盘,避免插入多个U盘时选错。
- 写入日志时用
"a"模式(追加写入),不会覆盖之前的历史数据,适合长期记录鱼菜共生系统的监测数据。 - 记得处理异常场景,比如U盘中途被拔出、没有写入权限等情况,避免程序崩溃。
内容的提问来源于stack exchange,提问作者user11226368




