【问题标题】:How to remove the last occurrence of "=" symbol from a property file using Python如何使用 Python 从属性文件中删除最后出现的“=”符号
【发布时间】:2020-07-21 06:45:50
【问题描述】:

这是我的属性文件的内容,文件名为 conf.properties

#A_Value='true'
#cache_locators='Server_name:1212'
#ssl_trustore='qa_client_truststore'
#ssl_password='ENC(kYE9WAv/HYjdw='=')'

我正在尝试将此属性文件转换为 json

将 conf.properties 转换为 json 的代码

import json
import sys
prop_file = "conf.properties"
import pathlib
file = pathlib.Path(prop_file)
if file.exists ():
    split_properties=[line.split("=") for line in open(prop_file)]
    properties={key: value for key,value in split_properties }
    print(json.dumps(properties))
else:
    print (prop_file+" not found")

由于config.properties 的最后一行有多个"=" 符号,我收到以下错误-

properties={key: value for key,value in split_properties }
ValueError: too many values to unpack (expected 2)

我需要删除config.properties最后一行出现的多次“=”符号

来自

#ssl_password='ENC(kYE9WAv/HYjdw='=')'

#ssl_password='ENC(kYE9WAv/HYjdw)'

【问题讨论】:

    标签: python python-3.x properties


    【解决方案1】:

    您可以在调用.split() 方法时指定需要多少个元素:

    line.split("=", maxsplit=1)
    

    这将拆分一次,这意味着您最终会得到最多两个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-11
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 2018-02-12
      • 1970-01-01
      相关资源
      最近更新 更多