简体   繁体   English

在 python 中的空 config.txt 文件中读取结果

[英]reading results in empty config.txt file in python

# read no. of requests
if(os.path.isfile("config.txt")):
        with open("config.txt", "r") as json_file:# Open the file for reading   
            configurations = json.load(json_file) # Read the into the buffer
            # info = json.loads(js.decode("utf-8"))
            print("read config file")
            if("http_requests_count" in configurations.keys()):
                print("present")
                print(configurations["http_requests_count"])
                number_of_requests = int(configurations["http_requests_count"])
                print(number_of_requests)

config.txt file from which i am reading我正在读取的 config.txt 文件

{
    "first_container_ip": "8100",
    "master_db" : "abc",
    "http_requests_count" : "8",
    "master_name" : "master",
    "slave_names" : ["slave1", "slave2", "slave3"]
}

later in the code, when i am opening the config file to write its giving me error like稍后在代码中,当我打开配置文件来编写它给我的错误时

io.UnsupportedOperation: not readable

and when i open the config file manually i find it to be empty...当我手动打开配置文件时,我发现它是空的...

In your full code example, you do在您的完整代码示例中,您可以

with open("config.txt", "w") as json_file:# Open the file for writing
    configurations = json.load(json_file) # Read the into the buffer

which will fail (can't read from a file opened for writing) and truncate the file (as opening with w does).失败(无法从为写入打开的文件中读取)截断文件(就像用w打开一样)。

This is why you get the UnsupportedOperation error, and why the file ends up being empty.这就是您收到 UnsupportedOperation 错误以及文件最终为空的原因。

I suggest refactoring things so you have two simple functions for reading and writing the configuration file:我建议重构一些东西,这样你就有两个简单的函数来读写配置文件:

def read_config():
    if os.path.isfile("config.txt"):
        with open("config.txt", "r") as json_file:
            return json.load(json_file)
    return {}


def save_config(config):
    with open("config.txt", "w") as json_file:
        json.dump(config, json_file)


def scaleup(diff):
    config = read_config()
    slave_name_list = config.get("slave_names", [])
    # ... modify things ...
    config["slave_names"] = some_new_slave_name_list
    save_config(config)


def scaledown(diff):
    config = read_config()
    slave_name_list = config.get("slave_names", [])
    # ... modify things...
    slave_name_list = list(set(slave_name_list) - set(slave_list))
    config["slave_names"] = slave_name_list
    save_config(config)

(As an aside, since you're doing Docker container management, consider using container labels themselves as the master data for your state management instead of a separate file that can easily go out of sync.) (顺便说一句,由于您正在执行 Docker 容器管理,请考虑使用容器标签本身作为您的 state 管理的主数据,而不是一个可以轻松 Z34D1F91FB2E514B8576FAB1A75A89A6B 不同步的单独文件。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM