我有一个以zip格式写入文件的程序。
with gzip.open(filename, "at") as jsonfile:
jsonfile.write(my_json+"n")
我的问题是:如果进程停止,我会写 200 行而不是 500 行(总数(。 我的愿望是:我想在再次运行程序时覆盖这 200 行,但这些行并不孤单(在使用程序之前有更多的文本(并添加其余的 (300(。我知道我必须在哪一行写(例如,我的程序开始在第 1000 行附加文本(......有什么方法可以做到这一点,例如:
with gzip.open(filename, "at") as jsonfile:
jsonfile.write(my_json+"n", append_text_after_this_line=="1000")
所以我以一个 1500 行的文件结束,而不是 1700 行,重复了 200 行。
您的问题有不同的解决方案
您可以计算已添加到文件中的行数,例如:
lines = 0
with gzip.open(filename, "rt") as f:
for lines, _ in enumerate(f, 1): pass
duplicated_lines = lines - append_after
with gzip.open(filename, "at") as jsonfile:
remaining_json = 'n'.join(my_json.split('n')[duplicated_lines:])
jsonfile.write(remaining_json + "n")