Python3读取out.txt存储的文件路径 结合for循环实现逐个文件上传
Python3 批量遍历上传文件实现方案
首先确保你已经导入所有依赖模块:
import os import json import requests
你已经定义好的上传配置(url、headers、options)保持不变,在原有代码基础上补充以下逻辑即可:
# 读取out.txt中的所有有效文件路径 with open("out.txt", "r", encoding="utf-8") as f: # 逐行处理:去除换行/空白字符、过滤空行 file_list = [line.strip() for line in f if line.strip()] # 逐个遍历上传 for file_path in file_list: # 输出指定格式的上传提示 print(f"uploading {file_path}...") try: # 复用你原有单文件上传逻辑 with open(file_path, "rb") as sample: payload = { "options": (None, json.dumps(options), "application/json"), "filename": (os.path.basename(file_path), sample, "application/octet-stream") } response = requests.request("POST", url, headers=headers, files=payload, verify=False) # 可选:放开下方注释可查看每个文件的上传状态码,方便排查问题 # print(f"{file_path} 上传完成,响应状态码:{response.status_code}") except Exception as e: # 异常捕获避免单个文件上传失败导致整体程序中断 print(f"{file_path} 上传失败,错误信息:{str(e)}")
注意事项
- 如果你的
out.txt是GBK编码,把打开文件的encoding="utf-8"替换为encoding="gbk"即可,避免路径读取乱码 - 不需要异常捕获的话可以直接删除
try-except包裹的结构即可 - 如果你需要根据上传响应做额外的业务逻辑,可以在请求发送完成后补充对
response的处理代码
内容的提问来源于stack exchange,提问作者HIMANSHU CHORSIYA
相关产品推荐
相关产品推荐

