Vip*_*ani 4 python configparser python-2.7
我正在使用一个文件,我有一个名为DIR的部分,其中包含路径.EX:
[DIR]
DirTo=D:\Ashish\Jab Tak hai Jaan
DirBackup = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Backup
ErrorDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Error
CombinerDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Combiner
DirFrom=D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\In
PidFileDIR = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Pid
LogDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Log
TempDir = D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Temp
Run Code Online (Sandbox Code Playgroud)
现在我想要替换我已经完成它的路径,但是当我替换它在新写入的.ini文件中的分隔符之前和之前给我空格.例如:DirTo = D:\Parser\Backup.我如何删除这些空格?
码:
def changeINIfile():
config=ConfigParser.RawConfigParser(allow_no_value=False)
config.optionxform=lambda option: option
cfgfile=open(r"D:\Parser\ERICSSON_CSCORE_STANDARD_VMS\Windows\opx_PAR_GEN_660_ERICSSON_CSCORE_STANDARD_PM_VMS_MALAYSIA.ini","w")
config.set('DIR','DirTo','D:\Ashish\Jab Tak hai Jaan')
config.optionxform=str
config.write(cfgfile)
cfgfile.close()
Run Code Online (Sandbox Code Playgroud)
Jos*_*hua 10
我遇到了这个问题,我想出了一个额外的解决方案.
相反,我在文件对象周围编写了一个包装器,它在所有写入的行中简单地将"="替换为"=".
class EqualsSpaceRemover:
output_file = None
def __init__( self, new_output_file ):
self.output_file = new_output_file
def write( self, what ):
self.output_file.write( what.replace( " = ", "=", 1 ) )
config.write( EqualsSpaceRemover( cfgfile ) )
Run Code Online (Sandbox Code Playgroud)
这是 的定义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")
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,%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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4887 次 |
| 最近记录: |