如何让Python字典转YAML时仅按\n拆分字符串?
解决方案
问题核心在于两点:一是禁止PyYAML自动折行长字符串(默认宽度限制导致),二是让原字符串中的\n转换为实际换行而非保留转义标识。以下是两种实现方案:
方案1:使用YAML字面量样式(推荐,符合YAML规范)
通过自定义字符串代表器,让包含换行的字符串以|字面量样式输出,同时禁用自动折行:
import yaml from yaml.representer import SafeRepresenter # 自定义代表器:含换行的字符串用字面量样式输出 def str_with_newline_representer(dumper, data): if '\n' in data: return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dumper.represent_scalar('tag:yaml.org,2002:str', data) # 注册代表器到safe_dump SafeRepresenter.add_representer(str, str_with_newline_representer) # 修正拼写错误后的字典数据 d = {'test': {'long_string':'this is a long string that does not successfully split when it sees the character \n which is an issue'}} # 导出YAML with open('./test.yaml', 'w+') as ff: yaml.safe_dump(d, ff, width=float('inf'))
输出的YAML内容:
test: long_string: | this is a long string that does not successfully split when it sees the character which is an issue
方案2:强制双引号包裹并换行
如果需要保持双引号包裹的格式,自定义代表器直接输出带换行的双引号字符串:
import yaml from yaml.representer import SafeRepresenter def quoted_multiline_str_representer(dumper, data): if '\n' in data: # 拆分字符串并处理换行后的缩进对齐 lines = data.split('\n') formatted = [f'"{lines[0]}'] + [' ' * 16 + line for line in lines[1:]] formatted[-1] += '"' return dumper.represent_scalar('tag:yaml.org,2002:str', '\n'.join(formatted), style='') return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='"') SafeRepresenter.add_representer(str, quoted_multiline_str_representer) d = {'test': {'long_string':'this is a long string that does not successfully split when it sees the character \n which is an issue'}} with open('./test.yaml', 'w+') as ff: yaml.safe_dump(d, ff, width=float('inf'))
输出的YAML内容:
test: long_string: "this is a long string that does not successfully split when it sees the character which is an issue"
关键参数说明
width=float('inf'):禁用PyYAML默认的80字符宽度限制,避免长文本被自动折行- 自定义代表器:控制字符串输出样式,将原字符串中的
\n转换为YAML中的实际换行,而非转义字符
内容的提问来源于stack exchange,提问作者Kspr
相关产品推荐
相关产品推荐

