Python: write to next empty line

I am trying to write the conclusion of what is being done on three large iterations, and every time I open and close the outfile. Counters get reset and similar things after iterations, and I'm a massive newb, and I will fight for it with the insidious code that I wrote. Therefore, even if it is slower, I would like to change the way it is output.

Currently, for output, it simply rewrites on the first line, so I only have the output of the last program run. (tau, output - variables, given values ​​in iterations above in the code)

with open(fileName + '.autocorrelate', "w") as outfile: outfile.writelines('{0} {1}{2}'.format(tau, output, '\n')) 

I was wondering if there are any quick ways to get python to check the first empty line when it opens the file and writes a new line there?

+4
source share
3 answers

At the end of the file will be written "a" instead of "w". This is a way not to overwrite.

+9
source

If you open the file in add mode: "a" instead of " w ", you can write a new line at the end of your file.

+1
source

You do something similar to save a link (line number) for each empty line in the file

 # Get file contents fd = open(file) contents = fd.readlines() fd.close() empty_line = [] i = 0 # find empty line for line in contents: if line == "": empty_line.append(i) i+=1 
0
source

Source: https://habr.com/ru/post/1415582/


All Articles