You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何高效检查文件列表并下载本地不存在的文件

核心需求
  • 遍历预存的模组文件名列表,校验Minecraft mods目录下对应文件是否存在
  • 匹配对应的下载链接列表,自动拉取本地缺失的模组文件
  • 实现多设备间的游戏模组自动同步更新

注:本次仅修复代码存在的语法、逻辑错误,暂不调整字典映射存储的优化方案。

现存代码问题
  • 缺失依赖导入:代码调用了os.getenv()但仅从os.path导入了exists方法,运行时会直接触发名称错误
  • 路径拼接风险:直接用字符串拼接Windows路径容易出现转义符冲突、遗漏路径分隔符的问题
  • 存储路径错误:下载模组时未指定目标mods目录,文件会被保存到脚本运行的当前工作目录,不会进入Minecraft的模组加载路径
  • 提示逻辑错误:无论模组是已存在跳过、还是新下载完成,都会统一打印“已存在跳过”的提示,无法反馈真实执行状态
  • 缺少基础容错:请求下载、文件读写操作没有做基础配置,遇到网络波动、权限不足时会直接中断整个流程
修正后可运行代码
import os
import requests
from os.path import exists

# 规范路径拼接,避免转义、斜杠匹配问题
modsPath = os.path.join(os.getenv('APPDATA'), '.minecraft', 'mods')
links = []
print("Grabbing Download Links...")
with open(os.path.join(modsPath, "master_downloads_list.txt"), "r", encoding="utf-8") as g:
    for line in g:
        line = line.strip()
        # 保留原代码的列表终止判断逻辑
        if 'str' in line:
            break
        links.append(line)
        print(f"Grabbed {line}")
print("Finished grabbing download links.")

with open(os.path.join(modsPath, "master_mods_list.txt"), "r", encoding="utf-8") as f:
    i = -1
    for line in f:
        line = line.strip()
        i = i + 1
        # 保留原代码的列表终止判断逻辑
        if 'str' in line:
            break
        mod_file_path = os.path.join(modsPath, line)
        # 模组已存在直接跳过
        if exists(mod_file_path):
            print(f"Mod {line} exists & is updated. Skipping.")
            continue
        # 模组不存在时执行下载
        print(f"Downloading missing mod: {line}")
        url = links[i]
        dl = requests.get(url, allow_redirects=True, timeout=30)
        # 写入到正确的mods目录
        with open(mod_file_path, 'wb') as mod_file:
            mod_file.write(dl.content)
        print(f"Successfully downloaded {line}")

内容的提问来源于stack exchange,提问作者Cal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 11:33:12