简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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