Closing a file

Duncan Smith buzzard at urubu.freeserve.co.uk
Thu Jul 20 15:57:27 EDT 2000


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