python - 使用 Python 字典处理文本文件并上传到正在运行的 Web 服务实验室
问题描述
我想编写一个 Python 脚本,它会自动上传反馈,而无需将其转换为字典。脚本现在应该遵循以下结构:
列出 /data/feedback 目录下的所有 .txt 文件,其中包含要在公司网站上显示的实际反馈。提示:为此使用 os.listdir() 方法,它返回指定路径中所有文件和目录的列表。
您现在应该有一个列表,其中包含路径 /data/feedback 中的所有反馈文件。遍历每个文件,并根据这些文本文件的内容,通过分别将标题、名称、日期和反馈作为内容值的键来创建字典。
现在,您需要一个包含键及其各自值(来自反馈文件的内容)的字典。这将通过 Django REST API 上传。
使用 Python requests 模块将字典发布到公司的网站。使用 request.post() 方法向 http:///feedback 发出 POST 请求。替换为 35.193.233.100。
确保不返回错误消息。您可以打印响应对象的 status_code 和文本来检查发生了什么。您还可以使用响应 status_code 201 来创建指示请求已成功的成功状态响应代码。
解决方案
#! /usr/bin/env python3
import os
import requests
dir="/data/feedback/"
url= "http://1.1.1.1/feedback/"
#IMPORTANT: Replace 1.1.1.1 with your
# Qwiklab's "corpweb" IP Address
for file in os.listdir(dir):
tipos = ["title","name","date","feedback"]
datos = {}
lineas = []
print(file)
with open(dir+"/"+file,"r") as txtfile:
x = 0
for line in txtfile:
datos[tipos[x]] = line.rstrip('\n')
x += 1
print(datos)
response = requests.post(url,json=datos)
推荐阅读
- php - 如何显示来自 PHPSECLIB 的 sftp-get 的 PDF 返回
- dart - 如何阻止我的应用返回启动画面
- regex - 正则表达式的计算复杂度
- websocket - 如何使用 websocket 通知客户端另一个客户端发起的请求?
- json - MongoDB中的高级搜索文本框
- c# - 突出显示 WPF Datagrid 中的选定项
- r - 如何在 Rcpp 中为 SEXP 参数设置默认值
- javascript - 在 javascript 和 html 中转义撇号(单引号)字符
- python - 为什么保存的模型在加载到 Keras 后以初始损失和准确率值开始?
- python - 为什么我尝试使用 xlrd 打开 Excel 工作簿时出现 KeyError