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