<h3>更新的答案</h3>
<p>我没有意识到你的输入是一本字典,你提到字典正在保存为文件。我假设代码中的字典查找引用了一个文件。如果您想从dict变成类似CSV文件的对象,需要做更多的工作</p>
<p>根据您问题的I/O,您的输入词典似乎具有以下结构:</p>
<p><code>file_data = {"name": {"Col1": 1, "Col2": 2}}</code></p>
<p>鉴于此,我建议使用<a href="https://docs.python.org/3/library/csv.html" rel="nofollow noreferrer">csv</a>和<a href="https://docs.python.org/3/library/io.html" rel="nofollow noreferrer">io</a>尝试以下操作:</p>
<pre class="lang-py prettyprint-override"><code>import csv
import io
import requests
session = requests.Session()
session.headers.update(
{"Authorization": user, "Content-Type": "application/octet-stream"}
)
file_data = {"name": {"Col1": 1, "Col2": 2}}
with io.StringIO() as f:
name = file_data["name"]
writer = csv.DictWriter(f, fieldnames=name)
writer.writeheader()
writer.writerows([name]) # `data` is dict but DictWriter expects list of dicts
response = session.put(url, data=f)
</code></pre>
<p>您可能希望使用请求头中传递的正确MIME类型进行测试。虽然端点可能不关心,但最好使用正确的数据类型。CSV应该是<code>text/csv</code>。Python还提供了<a href="https://docs.python.org/3.8/library/mimetypes.html" rel="nofollow noreferrer">MIME types module</a>:</p>
<pre class="lang-py prettyprint-override"><code>>>> import mimetypes
>>>
>>> mimetypes.types_map[".csv"]
'text/csv'
</code></pre>
<hr/>
<h3>原始答案</h3>
<p>只需以字节模式打开文件,而不用担心编码或读入内存</p>
<p>此外,使用上下文管理器来处理文件而不是分配给变量,并将头传递给<code>Session</code>对象,这样就不必在请求调用中重复传递头数据</p>
<p>关于PUT方法的文件:</p>
<p><a href="https://requests.readthedocs.io/en/master/api/#requests.put" rel="nofollow noreferrer">https://requests.readthedocs.io/en/master/api/#requests.put</a></p>
<blockquote>
<p>data – (optional) Dictionary, list of tuples, bytes, <strong>or file-like object</strong> to send in the body of the Request.</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>import requests
session = requests.Session()
session.headers.update(
{"Authorization": user, "Content-Type": "application/octet-stream"}
)
with open(file_data["name"], "rb") as f:
response = session.put(url, data=f)
</code></pre>
<p><em>注意:</em>我修改了您的代码,以便更紧密地遵循python风格指南</p>