python - 在 python 中读取空 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
# 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
当我手动打开配置文件时,我发现它是空的...
解决方案
在您的完整代码示例中,您可以
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 容器管理,请考虑将容器标签本身用作状态管理的主数据,而不是使用容易不同步的单独文件。)
推荐阅读
- python - 如何从来自 api 的嵌套 json 响应更改为数据框
- sql - 如何在 spark scala sql 中命名聚合列而不是默认给定的列?
- php - 下个月的查询值没有返回任何值?
- react-native - 当抽屉屏幕聚焦于 React-Native 时运行一些代码
- timestamp - Azure 数据工厂、复制数据、Teradata ODBC、日期时间时间戳映射
- reactjs - React Native:如何显示特定类别的帖子?
- python - 如何通过 BeautifulSoup 打印波斯语页面的文本?
- flutter - Flutter:当前 Flutter SDK 版本为 0.0.0-未知
- google-colaboratory - /bin/bash: ./darknet: No such file or directory 问题
- java - 为什么在迭代 HashMap 时在 IF 块中添加元素会起作用?