简体   繁体   English

如何在字典中将字典列表的内容写入文件

[英]How to write content of a list of dict into a file in python

I am getting the output as a list of dict from a db call and I want to write the output into a file with some configuration. 我正在从db调用获取作为dict列表的输出,我想将输出写入具有某些配置的文件中。 Example

my_dict = [{'pattern': "abc", 'message': "This is not possible"},
           {'pattern': "def", 'message': "The parameter provided application is invalid"},
           {'pattern': "ijk",'message': "Expected value for debugging"}
           ]
# want to write the op like below into some file.
# key's will be header also some case i need to ignore the headers.
pattern|message # file header
abc|This is not possible # file data
def|The parameter provided application is invalid # file data
ijk|Expected value for debugging # file data
with open('my.log', 'w') as log:
    log.write('pattern|message\n')
    for line in my_dict:
        log.write('{pattern}|{message}\n'.format(**line))

my.log 我的日志

pattern|message
abc|This is not possible
def|The parameter provided application is invalid
ijk|Expected value for debugging

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM