Detecting the first time I open/append to a file
Terry Reedy
tjreedy at udel.edu
Tue Sep 23 17:41:51 EDT 2008
tkpmep at hotmail.com wrote:
> I have a simulation that runs many times with different parameters,
> and I want to aggregate the output into a single file with one rub: I
> want a header to be written only the first time. My program looks a
> bit like this:
>
> def main():
> for param in range(10):
> simulate(param)
>
> def simulate(parameter):
> 'Lots of code followed by:
> with open(summaryFn, 'ab') as f:
> writer = csv.writer(f)
> writer.writerow(header)
> writer.writerow(Sigma)
>
>
> If I can sense that the file is being created in the first iteration,
> I can then use an if statement to decide whether or not I need to
> write the header. Question: how can I tell if the file is being
> created or if this its the first iteration? It's unrealistic to test
> the value of the parameter as in the real problem, there are many
> nested loops in main, and the bounds on the loop indices may change.
How about file.tell == 0? or have I misunderstood the requirement?
More information about the Python-list
mailing list