读取会导致python中的空config.txt文件
我正在读取的config.txt文件读取会导致python中的空config.txt文件,python,json,python-3.x,file,Python,Json,Python 3.x,File,我正在读取的config.txt文件 # 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 # in
# 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)
在代码的后面,当我打开配置文件编写它的giving me错误时,如
{
"first_container_ip": "8100",
"master_db" : "abc",
"http_requests_count" : "8",
"master_name" : "master",
"slave_names" : ["slave1", "slave2", "slave3"]
}
当我手动打开配置文件时,我发现它是空的…在您的完整代码示例中,是这样的
io.UnsupportedOperation: not readable
这将失败(无法从为写入而打开的文件中读取)并截断该文件(就像使用w
打开文件一样)
这就是为什么会出现UnsupportedOperation错误,以及文件最终为空的原因
我建议进行重构,这样您就可以使用两个简单的函数来读取和写入配置文件:
with open("config.txt", "w") as json_file:# Open the file for writing
configurations = json.load(json_file) # Read the into the buffer
(顺便说一下,既然您正在做DOCKER容器管理,请考虑将容器标签本身用作您的状态管理的主数据,而不是单独的文件,可以很容易地脱离同步。)
然后可能在您销毁配置文件的代码中;您在此处包含的部分中没有任何内容对此负责。io.UnsupportedOperation:not readable
并不表示文件为空,它表示读取文件时出现问题。如果要打开文件进行写入,则不能同时使用同一个对象进行读取。至少存在一个错误,即关闭json_文件两次。。使用json\u file.close()显式关闭一次,上下文管理器(使用语法)再次关闭该文件。@rasjani这不会导致error@B什么是毁灭?没有。我已经插入了代码的链接。看一看?哦,对了,这很有道理。但是,如何更新配置文件中的一个字段呢?Open for reading,read JSON,update in memory,Open for write,write JSON。@dagwood添加了一个示例。噢,谢谢,我来看看这个示例。但是如果我在w+模式下打开,然后使用与我编写的代码相同的代码会怎么样?在上面的示例中,您给出的save_config是什么
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)