如何用Python将URL中的图片保存到Azure Blob Storage ADLS Gen2
问题原因
你用open()函数直接写入abfss://开头的云存储路径,这个函数仅能操作本地文件系统,无法识别ADLS Gen2的路径格式,因此触发了FileNotFoundError。
解决方法
要直接将图片上传到Blob Storage(ADLS Gen2),需使用Azure官方的azure-storage-blob库操作云存储,而非本地文件读写函数。
步骤1:安装依赖
先安装Azure存储开发库:
pip install azure-storage-blob
步骤2:修改代码逻辑
替换原有的open()写入逻辑,改用Blob存储客户端直接上传下载的图片内容:
import requests from azure.storage.blob import BlobServiceClient # 替换为你的Blob存储连接字符串 connect_str = "你的Blob存储连接字符串" # 替换为你的文件系统名(对应abfss://后的datalake) file_system_name = "datalake" # Blob存储中的目标路径(对应production/xx/test/) target_blob_path = "production/xx/test/" # 初始化Blob服务客户端 blob_service_client = BlobServiceClient.from_connection_string(connect_str) # 获取文件系统客户端(ADLS Gen2的文件系统等价于Blob容器) file_system_client = blob_service_client.get_file_system_client(file_system=file_system_name) for index, row in data.iterrows(): url = row['url'] file_name = url.split('/')[-1] r = requests.get(url) if r.status_code == 200: # 构建完整的Blob路径 blob_full_path = f"{target_blob_path}{file_name}" # 获取Blob客户端 blob_client = file_system_client.get_blob_client(blob=blob_full_path) # 上传图片内容,overwrite=True表示覆盖同名文件 blob_client.upload_blob(r.content, overwrite=True) print(f"成功上传:{blob_full_path}") else: print(f"下载失败,URL:{url},状态码:{r.status_code}")
注意事项
- 连接字符串可在Azure门户的存储账户中获取:存储账户 → 访问密钥 → 连接字符串
- 若目标路径(
production/xx/test/)不存在,ADLS Gen2会自动创建对应层级结构,无需手动创建 - 确保Python环境拥有该存储账户的访问权限,可通过连接字符串(含密钥)或Azure AD身份验证授权
内容的提问来源于stack exchange,提问作者Youshikyou
相关产品推荐
相关产品推荐

