使用Python-Requests库上传文本文件

2 投票
1 回答
7429 浏览
提问于 2025-04-17 06:11

你好,我在用Python的Requests库上传一个文本文件时遇到了问题(http://docs.python-requests.org/en/latest/index.html),你能告诉我哪里出错了吗?

我试着搜索了一些相关的问题,找到了这个从Python脚本发送文件的POST请求,但它没有回答我的问题。

这是我的代码:

import codecs
import requests

# Create a text file
savedTextFile = codecs.open('mytextfile.txt', 'w', 'UTF-8')

# Add some text to it
savedTextFile.write("line one text for example\n and line two text for example")

# Post the file THIS IS WHERE I GET REALLY TRIPPED UP
myPostRequest = requests.post("https://someURL.com", files=savedTextFile)

我尝试了几种不同的写法,但每次都会出现新的错误。我该怎么上传我刚创建的这个txt文件呢?我想要上传的API要求必须上传一个文本文件。

任何帮助都非常感谢!

1 个回答

5

files参数需要一个字典,这个字典的内容是文件名和文件处理器的对应关系。这个在源代码中有说明(目前在第69行):

Github 源代码 (requests/models.py)

#: Dictionary of files to multipart upload (``{filename: content}``).
self.files = files

有时候,最好的文档就是代码本身。

你最后一行的代码应该像下面这样:

myPostRequest = requests.post("https://someURL.com", files={'mytextfile.txt': savedTextFile})

撰写回答