【问题标题】:Eliminating spaces between equal signs in ConfigParser - Python [duplicate]消除ConfigParser中等号之间的空格-Python [重复]
【发布时间】:2015-10-30 16:02:33
【问题描述】:

我从this 帖子中得到了一个很好的答案,涵盖了我想要的一切。

[Box]
box.active = false
resolution_tracker.active = true
box.api_key = 
box.api_secret = 
box.job_interval = 480
box.max_attempts = 6
box.users = 

[Google]
google.active = true
google.job_interval = 480
google.users = <useremail>
google.key_file_name = <key_file>
google.service_account_id = <account_id>

但是,仍然存在的问题是如何删除相等分配中的空格。例如:

box.active = false

必须

box.active=false

就是这样,我想删除= 之间的空格。 .properties 文件是在 Python 中使用 ConfigParser 生成的,但这些空白似乎正在产生问题。当然,我可以使用其他东西来删除那些空白,但是使用StringIOConfigParser 或任何其他Python 库是否有更优雅的解决方案?

** 编辑 ** 这个问题不是重复的,因为我们试图找到一种更简单的方法来使用 API 删除 = 周围的空格,而不是重写 ConfigParser 类。

【问题讨论】:

标签: python templates


【解决方案1】:

ConfigParser.write() 有一个标志

#!/usr/bin/env python3
import sys
from configparser import ConfigParser
from io import StringIO


CONFIG = '''
[Box]
box.active = false
resolution_tracker.active = true
box.api_key = 
box.api_secret = 
box.job_interval = 480
box.max_attempts = 6
box.users = 

[Google]
google.active = true
google.job_interval = 480
google.users = <useremail>
google.key_file_name = <key_file>
google.service_account_id = <account_id>
'''

parser = ConfigParser()
parser.readfp(StringIO(CONFIG))
parser.write(sys.stdout, space_around_delimiters=False)

输出:

[Box]
box.active=false
resolution_tracker.active=true
box.api_key=
box.api_secret=
box.job_interval=480
box.max_attempts=6
box.users=

[Google]
google.active=true
google.job_interval=480
google.users=<useremail>
google.key_file_name=<key_file>
google.service_account_id=<account_id>

【讨论】:

  • 你确定吗? parser.write(configfile, space_around_delimiters=False):TypeError: write() got an unexpected keyword argument 'space_around_delimiters'
  • @philippe 这是一个 python3 脚本 - 你需要那个用于 python2 的脚本吗?
  • 是的..我使用的是import ConfigParser
  • @我已经安装了configparserpip,这解决了问题。
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多