【发布时间】:2023-03-10 06:23:01
【问题描述】:
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()
上面是类中的一个函数。另外,内容已经写在my_dic.txt中了。
A:Contents of B
B:Contents of B
我想通过上面的函数添加内容。但是这里有一个问题。我要把C到E的内容加进去,我希望的理想情况如下。
A:Contents of B
B:Contents of B
C:Contents of C
D:Contents of D
E:Contents of E
但是,如果我使用上面的函数,结果如下。
A:Contents of B
B:Contents of BC:Contents of C
D:Contents of D
E:Contents of E
我又试着写了一个转义码,但这次是这样。
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
我对此感到很困扰。怎么解决?
【问题讨论】:
-
您是否愿意接受有关如何以合理方式存储数据的建议?
-
你需要从文件中读取最后一个字符并检查它是否是换行符,如果不是则写一个......