Closing a file

Penfold spam at spam.com
Thu Jul 20 18:10:35 EDT 2000


Im assuming youre using Pythonwin (given that you say you need to "close
down python")
The problem is that you've set stdout to the file, then you never explicitly
close the file with a
outputfile.close()

So since something still refers the file it is never destructed and hence
closed.
Solutions
(i) Reset stdout to its default
[sys.stdout = sys._stdout]

This will mean the file gets closed after leaving your function (as nothing
refers to it anylonger).
For maximum safety you really should do an explicit outputfile.close() as
well

> I am attempting to write data to a file so I can export it to another
> application after running a simulated annealing algorithm.  (self.cost ==
0
> on the first iteration only.)  The relevant code is below.  The file seems
> to be created and written to O.K., bit it's not closed and I can't access
> 'simresults.txt' without shutting down Python.  I've checked the FAQ etc.
> but I'm no computer scientist and I can't figure out where I'm going
wrong.
> Thanks in advance for any help.
>
>
> from Numeric import *
> from Set import *
> from RandomArray import *
> import sys
>
>     def acceptsim(self, cost, n):
>         t = 10000.0 / n
>         if self.cost == 0:
>             outputfile = open('simresults.txt', 'w')
>             sys.stdout = outputfile
>             self.cost = DJT.totalcost(self)
>             self.low_cost = self.cost
>             self.low_ordering = self.ordering[:]
>         if n > 900000:
>             outputfile.close()
>             return 'stop'
>         if cost > 0:
>             p = exp ((-1 / t) * (float(cost) / self.cost))
>             if random() > p:
>                 print self.cost
>                 return 0
>             else:
>                 self.cost = self.cost + cost
>                 print self.cost
>                 return 1
>         else:
>             self.cost = self.cost + cost
>             if self.cost < self.low_cost:
>                 self.low_cost = self.cost
>                 self.low_ordering = self.ordering[:]
>             print self.cost
>             return 1
>
>





More information about the Python-list mailing list