如何从python中的多个文件创建字典并通过http发布

2024-04-27 23:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个POST请求,它将在我的web服务器上创建一个对象,该对象有几个属性,这些属性都是从不同的文件中提取的,每个文件都有一个自我解释的名称

我有以下文件结构

augmentations

  team_1

     objects

       category.txt
       description.txt
       location.txt
       orientation.txt
       title.txt

循环之后,应该有一个字典,其中包含每个文件的属性,我可以使用它将数据作为request.POST(“url”,params=parameter)中的param发布

我做了一些研究,但没能找到解决我问题的适当办法。根据https://www.w3schools.com/python/python_dictionaries.asp,您可以像我的代码中那样向库中添加键

# -*- coding: utf-8 -*-

import os
import requests

rootdir = 'C:/.../augmentations'

FileType = 'route'
parameter = {}

for subdir, dirs, files in os.walk(rootdir):
for directory in dirs:
    for file in files:
        if file == 'category.txt' and FileType not in subdir:
            f = open(os.path.join(subdir, file), "r", encoding='utf8')
            lines = f.readlines()
            f.close()
            x = ""
            for line in lines:
                line = line.replace(' ', '')
                x += line
            parameter["category"] = x
        elif file == 'description' and FileType not in subdir:
            f = open(os.path.join(subdir, file), "r", encoding='utf8')
            lines = f.readlines()
            f.close()
            x = ""  # input
            for line in lines:
                x += line
            parameter["description"] = x
        elif file == 'location' and FileType not in subdir:
            f = open(os.path.join(subdir, file), "r", encoding='utf8')
            lines = f.readlines()
            f.close()
            lineArray = []
            for line in lines:
                line = line.replace(' ', '')
                lineArray = line.split(',')
            parameter["lat"] = lineArray[0]
            parameter["lng"] = lineArray[1]
        elif file == 'orientation' and FileType not in subdir:
            f = open(os.path.join(subdir, file), "r", encoding='utf8')
            lines = f.readlines()
            f.close()
            lineArray = []
            for line in lines:
                line = line.replace(' ', '')
                lineArray = line.split(',')
            parameter["x"] = lineArray[0]
            parameter["y"] = lineArray[1]
            parameter["z"] = lineArray[2]
        elif file == 'title' and FileType not in subdir:
            f = open(os.path.join(subdir, file), "r", encoding='utf8')
            lines = f.readlines()
            f.close()
            x = ""  # input
            for line in lines:
                x += line
            parameter["title"] = x
    print(parameter)

问题是不知道信息块的终点,字典已经准备好交付了。我需要在哪里放置:

r = requests.post("myurl", params=parameters)

我从上一次打印得到的输出只有{category':'culture'} 输出应该是

{'category': 'culture', 'description': 'some description', 'title': 'some title', 'x': '0.123', 'y': '0.891', 'z': '0.871', 'lat': '40.01231', 'lng': '30.0000'}

对于每个对象(大约100个)

已解决-编辑:

问题是我忘记在elif条件中添加.txt


Tags: andintxtforparametertitleosline