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

Python循环生成带变量XML文件并写入Azure Blob指定目录问题

问题原因

  1. os.path.join() 规则问题:如果传入的路径段以/开头,会被识别为绝对路径,自动丢弃前面所有的路径前缀,你写的"/newDirectoryorFolder"带前导斜杠,导致拼接出的路径完全不符合预期
  2. 函数名拼写错误:你定义的函数名为createXMLfile(),调用时写的是creatXMLfile(),少了字母e,会直接触发函数不存在报错
  3. 目标目录不存在:如果指定的子目录未提前创建,直接写入文件会触发IO错误

修复方案

场景1:你是将Azure Blob容器挂载为本地目录(如用blobfuse),直接写入挂载路径

修改后的完整代码如下:

import os
import xml.etree.ElementTree as xml

# 提前定义固定路径参数,避免循环内重复生成
SAVE_ROOT = '/this/is/a/directory/thatsends/filestoAzureContainer'
TARGET_SUB_DIR = 'newDirectoryorFolder'
# 拼接完整目标目录,提前创建避免写入报错
full_target_path = os.path.join(SAVE_ROOT, TARGET_SUB_DIR)
os.makedirs(full_target_path, exist_ok=True)

for x in range(0, 75, 3):
    forecast = x * 3600
    model = model1
    try:
        forecast_hour = f"{int(forecast/3600)}h"
        date_run_stamp = date_formatted.strftime("%Y%m%d_%H") 

        # 生成XML
        root = xml.Element("Data")
        tree = xml.ElementTree(root)

        # 拼接完整文件路径
        file_name = f"{model}_{date_run_stamp}_{forecast_hour}.xml"
        complete_file_path = os.path.join(full_target_path, file_name)
        # 写入文件
        with open(complete_file_path, "wb") as f:
            tree.write(f)

    except Exception as e:
        # 打印具体错误方便排查
        print(f"Warning: unable to create file for forecast hour '{forecast}', error info: {str(e)}")

场景2:你是直接调用Azure Blob SDK上传,不需要本地存文件

Azure Blob没有真实的目录结构,所谓子目录就是给blob名称加前缀即可,示例代码:

import xml.etree.ElementTree as xml
from azure.storage.blob import BlobClient

# 配置参数
AZURE_CONN_STR = "你的Azure存储账户连接字符串"
CONTAINER_NAME = "你的Blob容器名称"
TARGET_SUB_DIR = "newDirectoryorFolder"

for x in range(0, 75, 3):
    forecast = x * 3600
    model = model1
    try:
        forecast_hour = f"{int(forecast/3600)}h"
        date_run_stamp = date_formatted.strftime("%Y%m%d_%H") 

        # 生成XML
        root = xml.Element("Data")
        xml_content = xml.tostring(root)

        # 拼接Blob名称,子目录直接加在前面用/分隔即可,不需要提前创建目录
        file_name = f"{model}_{date_run_stamp}_{forecast_hour}.xml"
        blob_name = f"{TARGET_SUB_DIR}/{file_name}"

        # 上传到Blob
        blob_client = BlobClient.from_connection_string(AZURE_CONN_STR, CONTAINER_NAME, blob_name)
        blob_client.upload_blob(xml_content, overwrite=True)

    except Exception as e:
        print(f"Warning: unable to upload file for forecast hour '{forecast}', error info: {str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 13:39:00