There is a list of dictionaries:

result = [{'1st_k': '1st_v', '2nd_k': '2nd_v', '3rd_k': '3rd_v'}, {'1st-k': '1st-v', '2nd-k': '2nd-v', '3rd-k': '3rd-v'}, {'1st.k': '1st.v', '2nd.k': '2nd.v', '3rd.k': '3rd.v'}] 

How is it more correct to write to a text file to get something like this:

 1st_k: 1st_v 2nd_k: 2nd_v 3rd_k: 3rd_v 1st-k: 1st-v 2nd-k: 2nd-v 3rd-k: 3rd-v 1st.k: 1st.v 2nd.k: 2nd.v 3rd.k: 3rd.v 

That is, each pair of ключ: значение dictionary should be written on a new line, and between each dictionary should be an empty line. So far, I write this:

 with open('test.txt', 'w', encoding='utf-8') as file: for record in result: for key, value in record.items(): file.write(f'\n{key}: {value}') file.write('\n') 

But I do not know how effective it is, plus at the beginning and at the end of the file, empty lines appear that I have to cut. Thanks in advance for your help.

    2 answers 2

    Here is an option very similar to your decision:

     In [174]: def f(d): ...: return '\n'.join('{}: {}'.format(k,v) for k,v in d.items()) ...: In [175]: txt = '\n\n'.join(map(f, result)) In [176]: print(txt) 1st_k: 1st_v 2nd_k: 2nd_v 3rd_k: 3rd_v 1st-k: 1st-v 2nd-k: 2nd-v 3rd-k: 3rd-v 1st.k: 1st.v 2nd.k: 2nd.v 3rd.k: 3rd.v 

    Well, write to the file:

     file.write(txt) 

    If there is any doubt that txt will fit in memory, then it is better to write one element to the file.

      Your solution is quite effective: with I / O, performance is no longer dependent on the code, but on the speed of the external device.

      In order not to form empty lines at the beginning, do not wrap the line before the output, but after:

       file.write(f'{key}: {value}\n') 

      I can also suggest using print instead of write , then the line break will be added automatically (again, at the end of the output line):

       print(f'{key}: {value}', file=file) 

      If the extra line break at the end of the file is very disturbing, then you can add a check that the last dictionary is displayed, and if so, do not translate the line after it:

       for i, record in enumerate(result): for key, value in record.items(): print(f'{key}: {value}', file=file) if i < len(result)-1: # Для длины N элементов последний элемент будет иметь индекс N-1 print(file=file)