简体   繁体   English

如何在某些行号之后覆盖/附加行?

[英]How to overwite/append lines after certain line number?

I am having a program that write to file in zip format.我有一个程序以 zip 格式写入文件。

 with gzip.open(filename, "at") as jsonfile:
      jsonfile.write(my_json+"\n")

my problem is: if the process stop I write 200 lines instead of 500 (the total).我的问题是:如果进程停止,我会写 200 行而不是 500 行(总计)。 my desire is: I want to overwite those 200 lines when running the program again, but those line are not alone (there is more text previous to the use of the program) and add the rest (300).我的愿望是:我想在再次运行程序时覆盖这 200 行,但这些行并不孤单(在使用程序之前还有更多文本)并添加 rest(300)。 I know in which line I have to write ( for example, my program started appending text in line 1000)... Is there any method to do this, like:我知道我必须在哪一行写(例如,我的程序开始在第 1000 行附加文本)......有没有什么方法可以做到这一点,比如:

 with gzip.open(filename, "at") as jsonfile:
      jsonfile.write(my_json+"\n", append_text_after_this_line=="1000")

So I ended with a file with 1500 lines instead of 1700 with 200 lines duplicated.所以我以一个 1500 行的文件结束,而不是 1700 行重复 200 行的文件。

there are different solutions to your problem您的问题有不同的解决方案

You can count how many lines you have already added to your file, for example:您可以计算已经添加到文件中的行数,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM