python - 将文本从一个文件传输到另一个文件
问题描述
我在将 dist 参数从输入文件传输到结果文件到输入文件中的相同位置时遇到问题我的代码是:
import requests
import json
import time
with open("query4.txt", "rt") as file:
data_file = file.read()
with open("result.txt", "w") as f_o:
for line in data_file.split("\n"):
for i in range(1):
drX, drY, fromX, fromY, dist = line.split(",")
url = "https://api.openrouteservice.org/directions?"
params = [
["api_key", "my_api_key"],
["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
["profile", "driving-car"]
]
headers = {
"Accept": "application/json, application/geo+json,"
"application/gpx+xml, img/png; charset=utf-8"}
responce = requests.get(url=url, params=params, headers=headers)
print(responce.url)
# print(responce.text)
result = json.loads(responce.text)
print(result)
for rows in result["routes"]:
print(rows["summary"]["distance"], file=f_o) # depending on how do you want the result
# print(result["routes"])
time.sleep(0)
输入样本:
48.94205856,38.48511505,48.94167600,38.49207300,511
46.54586411,30.64417267,46.53338808,30.65455914,1599
50.06436157,31.44526100,50.07415641,31.45929694,1482
50.35911942,30.94097710,50.33576900,30.95166500,2706
50.35837936,30.94162369,50.33576900,30.95166500,2614
作为现在的输出,我与摘要 json 有一段距离,例如
123.2
122.5
221
312.7
212
我想得到这个
123.2 125
122.5 122
221 340
312.7 300
212 220
我用过这个,但它似乎不起作用:
with open("query4.txt") as f:
input_file = f.read()
with open("result.txt", "w") as f1:
for line in input_file.split("\n"):
for line in f:
dX, dY, fX, fY, dst = line.split(",")
if "dst" in line:
f1.write(line)
解决方案
您只需将dist
变量添加到打印命令。此外,还有一些改进可以为您的代码带来:
import requests
import json
url = "https://api.openrouteservice.org/directions?"
headers = {"Accept": "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8"}
with open("query4.txt", "rt") as f_i, open("result.txt", "w") as f_o:
for line in f_i:
drX, drY, fromX, fromY, file_dist = line.split(",")
params = [
["api_key", "my_api_key"],
["coordinates", "%s,%s|%s,%s" % (drY, drX, fromY, fromX)],
["profile", "driving-car"]
]
response = requests.get(url=url, params=params, headers=headers)
result = json.loads(response.text)
for rows in result["routes"]:
f_o.write("{from_api} - {from_file}\n".format(from_api = rows["summary"]["distance"], from_file = file_dist) )
如果你想知道格式化部分,看看那里:https ://realpython.com/python-string-formatting
推荐阅读
- c# - 根据我的api返回的内容设置我的属性变量并填充动态创建的变量
- visual-studio-code - VSCode Intellisense 在 Jupyter Notebook Extension(MacOS)中不起作用
- python - 在OpenCV python中绘制最大面积轮廓的质心
- sql - 从特定键开始选择记录
- mysql - 对于按主键索引的顺序放置分区键的位置是否有一般规则?
- mysql - 我想在 MySQL 上的 while 条件中添加一个属性
- html - 如何在 HTML 中使用 div 标签
- amazon-redshift - 在 Redshift 中查找下一个最旧的行
- linux - 使用服务在 .bash 中启动 .sh 或在服务中启动 .sh 文件
- typescript - 异步函数需要 Visual Studio 2019 中的“Promise”构造函数