How to write a dictionary into an existing file?

后端 未结 4 732
-上瘾入骨i
-上瘾入骨i 2020-12-10 03:36

Let\'s say I have a dictionary and I want to write it into an existing file. How can I do so without losing anything that could potentially already exist in the file? What I

4条回答
  •  一个人的身影
    2020-12-10 03:59

    If you want to append a text representation of each key-value pair in the dictionary into a text file you could look into the following approach:

    def write_report(r, filename):
        input_file=open(filename, "a")
        for k, v in r.items():
            line = '{}, {}'.format(k, v) 
            print(line, file=input_file)        
        input_file.close()
    

    The above can be expressed more cleanly with the with statment.

    def write_report(r, filename):    
        with open(filename, "a") as input_file:
            for k, v in r.items():
                line = '{}, {}'.format(k, v) 
                print(line, file=input_file)
    

提交回复
热议问题