【发布时间】:2015-10-23 22:43:33
【问题描述】:
我正在使用 python 从 excel 中读取值并使用 yaml.safe_dumps 生成 yaml 文件。
问题 - 我希望在 yaml 文件中以单引号显示一个值。例如:'test'.
我尝试了几个选项,我得到的输出为'''test''' 或test 或!python/unicode 'test'
知道如何让单引号显示在 yaml 文件中。
完整代码如下:
import yaml
class RDF:
def __init__(self):
self.test = "test"
def create_TDF(self):
tdf_file_names_new_list = {}
tdf_file_names_new_list['ID'] = ""
tdf_file_names_new_list['name'] = ""
varname = 'test'
test_name = 'test1'
test_type = 'single'
test_definition_data = dict(
testName = "",
innerFilterName = 'inner filter',
testType = "",
analysisType = "",
testInformation = {})
test_definition_data['testInformation']['p']={}
p_dict={}
p_dict['VarName'] = varname
p_dict['VFile'] = 'file'
p_dict['affected'] = 'T'
test_definition_data['testInformation']['p'] = p_dict
test_definition_data['testInformation']['m']={}
test_definition_data['testInformation']['m']['VarName']=varname
test_definition_data['analysisType'] = 'T'
test_definition_data['testName'] = test_name
# The "testType" value is what i want to display in "single quotes".
# tried str(row[3].value) -> output still does not display single quotes.
# if i change "yaml.safe_dump" statement below to ---> tdf_yaml_file.write(yaml.dump(test_definition_data)) then the output is ---> testType: !!python/unicode 'Hypotonia'
test_definition_data['testType'] = test_type
with open('TDF_1'+'.tdf',"w") as tdf_yaml_file:
tdf_yaml_file.write(yaml.safe_dump(test_definition_data,encoding='utf-8', allow_unicode=False))
#tdf_yaml_file.write(yaml.dump(test_definition_data))
tdf_yaml_file.close()
def main():
tdf = RDF()
tdf.create_TDF()
if __name__ == '__main__':
main()
【问题讨论】:
-
请修改您的代码示例,使其独立工作,并展示您的工作——例如,对于您实际获得的输出,显示每个输入对应的输入。
-
也就是说——虽然 yaml 模块的工作是能够序列化所有可能的 YAML 值(在记录的约束范围内),但它的工作不是将它们序列化为特定的表示。如果它选择的表示反序列化为原始值,则序列化程序已经完成了它的工作,无论该表示看起来是否像您想要的那样。
-
@CharlesDuffy - 我添加了代码。谢谢。
-
我没有要你的原始代码;相反,我要求提供足以独立运行的样本。请参阅 sscce.org 或 stackoverflow.com/help/mcve 讨论如何构建一个最小的、完整的、可验证的示例(或 SSCCE 术语中的简短、独立、正确的示例)。
-
另外,由于这不包括
Test.xlsx,它仍然不足以独立运行(因此,它在 MCVE 术语中是不可验证的,或者不是在 SSCCE 术语中是自包含的)。您最好完全去掉 Excel 读取组件,并仅硬编码足够的数据来演示该错误。