我有一个配置文件,当我写入它时,它有空格
答案 0 :(得分:4)
以下是RawConfigParser.write
的定义:
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s = %s\n" %
(key, str(value).replace('\n', '\n\t')))
fp.write("\n")
如您所见,%s = %s\n
格式已硬编码到函数中。我认为你的选择是:
RawConfigParser
write
方法
如果您100%确定选项1不可用,则可以选择执行选项3:
def remove_whitespace_from_assignments():
separator = "="
config_path = "config.ini"
lines = file(config_path).readlines()
fp = open(config_path, "w")
for line in lines:
line = line.strip()
if not line.startswith("#") and separator in line:
assignment = line.split(separator, 1)
assignment = map(str.strip, assignment)
fp.write("%s%s%s\n" % (assignment[0], separator, assignment[1]))
else:
fp.write(line + "\n")