python-3.x - 如何使用 python 的 configparser 编写没有节的文件
问题描述
我需要使用 python 修改配置文件。该文件的格式类似于
property_one = 0
property_two = 5
即没有任何部分名称。
Python 的 configparser 模块不支持无节文件,但我可以使用它来轻松加载它们,使用这里的技巧:https ://stackoverflow.com/a/26859985/11637934
parser = ConfigParser()
with open("foo.conf") as lines:
lines = chain(("[top]",), lines) # This line does the trick.
parser.read_file(lines)
问题是,我找不到一种干净的方法将解析器写回没有节标题的文件。我目前最好的解决方案是将解析器写入StringIO
缓冲区,跳过第一行,然后将其写入文件:
with open('foo.conf', 'w') as config_file, io.StringIO() as buffer:
parser.write(buffer)
buffer.seek(0)
buffer.readline()
shutil.copyfileobj(buffer, config_file)
它可以工作,但有点难看,并且涉及在内存中创建文件的第二个副本。有没有更好或更简洁的方法来实现这一目标?
解决方案
偶然发现了一种不那么丑陋的方法:
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
config_file.write(text)
推荐阅读
- ios - WKWebView 发布请求 Swift 5
- css - 回退以适应整个浏览器宽度
- reactjs - React w/Typescript: useReducer, Action Interface w/ Union Type
- python - python:基于匹配两个数据集中的多个列合并两个数据库并在结果上应用脚本
- python-3.x - 将包含mp3歌曲的python文件转换为可执行文件
- swift - swiftui为什么不能分配可选?
- mapbox - 添加 Maki 图标而不是 Mapbox 地理编码器标记
- ruby-on-rails - 如何在postgresql rails中搜索具有多个值的数组列
- html - Angular如何使表头变粘
- javascript - Sendgrid API:如何发送带有单个模板数据的批量电子邮件?