A simple question about the indentation problem in txt

Viewed 43
def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    for j in range(len(re_doc2)):
        f2.write(re_doc2[j]+':'+def_lst[j])
    f2.close()

Above is a function within a class. Also, the content is already written in my_dic.txt.

A:Contents of B
B:Contents of B

I want to add content through the above function. But there was a problem here. I'm going to add the contents from C to E. The ideal situation I hope for is as follows.

A:Contents of B
B:Contents of B
C:Contents of C
D:Contents of D
E:Contents of E

However, if I use the above function, it comes out as follows.

A:Contents of B
B:Contents of BC:Contents of C
D:Contents of D
E:Contents of E

I tried writing an escape code again, but this time it comes out like this.

def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    for j in range(len(re_doc2)):
        f2.write('\n'+re_doc2[j]+':'+def_lst[j])
    f2.close()

A:Contents of B
B:Contents of B
C:Contents of C

D:Contents of D

E:Contents of E

I'm quite bothered by this. How can solve this?

2 Answers

You can write a '\n' before you write new lines to f2.

def sav_dic(self):
    f2 = open('my_dic.txt', 'a')
    f2.write('\n')
    for j in range(len(re_doc2)):
        f2.write(re_doc2[j]+':'+def_lst[j])
    f2.close()

Thanks for Matthias' comment. You can write it in this way:

def sav_dic(self):
    with open('my_dic.txt', 'a') as f2:
        f2.write('\n')
        for x, y in zip(re_doc2, def_lst):
            f2.write(f'{x}:{y}')
        

You can only write the newline for the first line you write

for j in range(len(re_doc2)):
    if j == 0:
        f2.write('\n')
    f2.write(re_doc2[j]+':'+def_lst[j])

Or update the code that writes my_dic.txt to always end lines with \n

Related