【问题标题】:reading results in empty config.txt file in python在 python 中读取空 config.txt 文件的结果
【发布时间】:2020-05-08 09:53:07
【问题描述】:
# 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 文件

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

稍后在代码中,当我打开配置文件来写它给我这样的错误

io.UnsupportedOperation: not readable

当我手动打开配置文件时,我发现它是空的......

【问题讨论】:

  • 那么可能稍后在代码中你会破坏你的配置文件;您在此处包含的部分中的任何内容都不会对此负责。
  • io.UnsupportedOperation: not readable 并不表示文件为空,它表示读取文件有问题。如果您正在打开文件进行写入,您也不能使用同一个对象来读取它。
  • 至少有一个错误,您要关闭 json_file 两次 .. 一次明确地使用 json_file.close() 和上下文管理器(with-syntax)再次关闭文件。
  • @rasjani 不会导致错误
  • @Błotosmętek 破坏?不我没有。我已经插入了我的代码的链接。看看?

标签: python json python-3.x file


【解决方案1】:

在您的完整代码示例中,您可以这样做

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

哪个失败(无法从打开的文件中读取)截断文件(就像用w打开一样)。

这就是您收到 UnsupportedOperation 错误以及文件最终为空的原因。

我建议重构一些东西,这样你就有两个简单的函数来读写配置文件:

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)

(顺便说一句,由于您正在执行 Docker 容器管理,请考虑使用容器标签本身作为您的状态管理的主数据,而不是一个容易不同步的单独文件。)

【讨论】:

  • 哦,对,这是有道理的。但是然后如何更新配置文件的字段之一。
  • 打开读取,读取 JSON,在内存中更新,打开写入,写入 JSON。
  • @dagwood 添加了一个示例。
  • 哦,谢谢,我会看看这个例子。但是如果我以 w+ 模式打开然后使用我编写的相同代码呢?
  • 你给出的上述示例中的 save_config 是什么
猜你喜欢
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多