我是 Python 新手,这是第一篇文章。想要将 TXT 文件上传到服务器,(截至目前,它是本地主机)。每次,我运行脚本,本地文件在服务器上上传和更新。我正在使用 Requests模块
import requests, time
url ='http://192.168.49.205/test/database/data.txt' # where i want to write
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
#r = requests.post(url,files=files) # this works too
r= requests.post('http://192.168.49.205/test/database/data.txt',
data={'upload_type': 'standard', 'upload_to': '0'},files=files)
print r.status_code
print r.text
data.txt 未更新。只看到旧数据(我在创建文件时输入了一些值)。我没有使用 PHP 或 HTML 中的任何表单。可以用方法上传吗?
相信,我在发布问题后有了一些清晰。现在,服务器端有 PHP 文件在监听客户端。这是“post.php”。因此,这将替换客户端的文本文件。 PHP 文件从客户端获取名称、任务、值并发布到服务器(本地)上的“a.txt”
<?php
if(isset($_GET["Name"])){
$name=$_GET["Name"];
}
if(isset($_GET["Task"])){
$task=$_GET["Task"];
}
if(isset($_GET["Value"])){
$value=$_GET["Value"];
}
$f=fopen("a.txt","w") or exit("Unable to open file!");
fwrite($f,$name);
fwrite($f," ");
fwrite($f,$task);
fwrite($f," ");
fwrite($f,$value);
fclose($f);
?>`
所以现在请求看起来像这样
import requests, time
url = 'http://192.168.49.205/test/test.php'
post_data = {'Name':'job','Task':'008','Value':'8'}
r= requests.post('http://192.168.49.205/test/post.php', data= post_data)
print r.status_code
print r.text
仍然没有达到“a.txt”的值。我错过了什么?请指教!
请您参考如下方法:
您没有阅读代码中的文件内容。 requests documentation状态:
files – (optional) Dictionary of ‘name’: file-like-objects (or {‘name’: (‘filename’, fileobj)}) for multipart encoding upload.
您的代码建议您使用第二个选项。然而:
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
您没有创建文档中指示的结构 - 您传递的是 3 个字符串的元组而不是 (string, file_obj) 的元组。您可能想这样做:
files = {'file':('data.txt',open('C:\Python27\data.txt','rb'))}
