首页 > 解决方案 > 将文件导入 json 密钥

问题描述

我希望我的程序进入一个文件并获取所有行并将它们放入一个 json 键中。

编码:

def import_proxies():
    global proxies_json
    proxies_json = {'http': {}}
    with open("proxies.txt", 'r', encoding='utf8') as proxy_file:
        for line in proxy_file:
            val = line.split()
            proxies_json[['http'][val]] = val
            print(proxies_json)


import_proxies()

My erorr: TypeError: list indices must be integers or slices, not list

我想要它做的是将文件行作为http键中的值导入(proxies_json = {'http': {}}

标签: python

解决方案


proxies_json 似乎是一本字典。所以这样的事情应该有效

def import_proxies():
    global proxies_json
    proxies_json = {'http': {}}
    with open("proxies.txt", 'r', encoding='utf8') as proxy_file:
        for line in proxy_file:
            val = line.split()
            data = proxies_json.get('http', {})
            for item in val:
                data[item] = item
            proxies_json['http'] = data
    print(proxies_json)

推荐阅读