Python 写入文件时如何正确保留换行与缩进格式?
model.yml写入时格式异常问题处理 场景说明
需要将固定结构的YML配置内容写入model.yml文件,要求保留正确的缩进层级与换行排版,但写入完成后出现异常:
\n、\t这类换行、缩进的转义字符直接以字面形式在文件中可见- 内容没有按照预期实现排版效果
原执行的代码逻辑:
content = """ REGISTER_DE: - DescriptionArea: - label: Hello Description - type: String - length: Long - required: False - Field3: - label: Date Field - type: Date - Field4: - type: TextAreaField - required: True - Field5: - type: String - length: Medium""" file = open('model.yml', 'w+') file.write(content)
错误输出结果
执行完上述代码后,model.yml生成的错误内容如下:
"\nREGISTER_DE:\n- DescriptionArea:\n - label: Hello Description\n - type: String\n\ \ - length: Long\n - required: False\n- Field3:\n - label: Date Field\n - type:\ \ Date\n- Field4:\n - type: TextAreaField\n - required: True\n- Field5:\n - type:\ \ String\n - length: Medium"
预期的正常文件格式
最终需要达成的排版正确、无多余转义字符的文件内容为:
REGISTER_DE: - DescriptionArea: - label: Hello Description - type: String - length: Long - required: False - Field3: - label: Date Field - type: Date - Field4: - type: TextAreaField - required: True - Field5: - type: String - length: Medium
修正方案
问题核心原因:写入的字符串并非原生多行文本,而是经过序列化、附带了外层引号和转义规则的字面表示;同时手动调用open()打开的文件未及时关闭,容易出现写入缓冲区异常,导致内容写入不符合预期。
可正常运行的修正代码:
# 定义原生多行字符串,不额外添加外层引号、手动拼接转义符 content = """REGISTER_DE: - DescriptionArea: - label: Hello Description - type: String - length: Long - required: False - Field3: - label: Date Field - type: Date - Field4: - type: TextAreaField - required: True - Field5: - type: String - length: Medium """ # 使用上下文管理器操作文件,自动处理句柄关闭,指定utf-8编码避免格式异常 with open('model.yml', 'w+', encoding='utf-8') as f: f.write(content)
内容的提问来源于stack exchange,提问作者Houy Narun
相关产品推荐
相关产品推荐

