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

使用Requests上传CSV文件时出现多余行问题求助

问题描述

我想用Python的requests库重写这条curl命令:

curl --show-error --fail-early --user "user:pswd" --upload-file path_to_file\file.csv https://domain/REST/upload

我写了下面的上传函数:

from pathlib import Path
from requests import HTTPBasicAuth
import requests

# url = 'https://domain/REST/upload/file.csv'    <- 包含文件名
def upload_file(file: Path, url: str, user: str, pswd: str) -> None:
    with open(file, 'rb') as f:
        response = requests.put(url, files={file.name: f},
                                auth=HTTPBasicAuth(user, pswd))

请求返回状态码200,响应文本是"OK",但传输后的CSV文件多了多余内容:

-- d2bba62dkvj39bccd207b6d229c4f3f2                                  
Content-Disposition: form-data; name="file.csv"; filename="file.csv" 

NAME;  AGE; HEIGHT
Leslie;34;  157
Ron;   50;  179
Tom;   38;  168
April; 20;  168

-- d2bba62dkvj39bccd207b6d229c4f3f2                                  

怎么去掉这些多余行?

解决方案

问题出在你用了files参数——这个参数会把请求内容编码成multipart/form-data格式(就是你看到的分隔线和头部信息),但curl的--upload-file是直接把文件原始二进制内容作为PUT请求的主体发送,没有额外的表单包装。

要和curl行为完全一致,直接把文件对象作为data参数传入,不要用files:

from pathlib import Path
from requests import HTTPBasicAuth, exceptions
import requests

def upload_file(file: Path, url: str, user: str, pswd: str) -> None:
    with open(file, 'rb') as f:
        try:
            response = requests.put(
                url,
                data=f,
                auth=HTTPBasicAuth(user, pswd),
                headers={"Content-Type": "text/csv"}  # 可选,明确指定内容类型
            )
            # 对应curl的--fail-early,主动抛出HTTP错误
            response.raise_for_status()
        except exceptions.RequestException as e:
            # 对应curl的--show-error,打印错误信息
            print(f"上传失败: {str(e)}")
            raise

关键说明:

  • data=f:直接将文件二进制内容作为请求体发送,和curl的--upload-file逻辑一致。
  • headers={"Content-Type": "text/csv"}:可选但推荐,明确告诉服务器接收的是CSV类型数据,避免自动推断可能出现的问题。
  • response.raise_for_status():当响应状态码非2xx时抛出异常,对应curl的--fail-early。
  • 捕获RequestException并打印错误,对应curl的--show-error。

这样上传后的CSV文件就不会有多余的分隔线和头部信息了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:44