0

I've done quite a bit of searching but I'm struggling to find a solution to my specific problem. I'm sure it's a pretty simple solution.

I am taking the best agent from a field in card playing game and playing it against other agents. The agent evolves in generations. So in each iteration I want to do the following:

create file named "results+generation number" i.e. results2
then I want to add the output from each function call on a new line
results from playing x = outputs1
results from playing y = outputs2

So I did indeed find a solution to the question but I'm running into another issue. When I run the program once, nothing is saved except the file name. The second time, the results from the first and so on.

  f = open("results_{0}.txt".format(counter),'w')
  f.write("Agent A vs. Champion\n"+"Champion wins = "+str(winsA1)+" Agent A wins = "+str(winsB1))
  f.write("\n\nAgent B vs. Champion\n"+"Champion wins = "+str(winsA2)+" Agent B wins = "+str(winsB2))
  f.write("\n\nRandom vs. Champion\n"+"Champion wins = "+str(winsA3)+" Random wins = "+str(winsB3))
  f.close
  • possible duplicate of [Creating a python file in a local directory](http://stackoverflow.com/questions/16430258/creating-a-python-file-in-a-local-directory) – DallaRosa Nov 15 '14 at 01:10
  • Actually there are so many question related to opening a file and writing to it that I don't really even know which to choose. – DallaRosa Nov 15 '14 at 01:11
  • 1
    Problem solved. with open(filename.txt) as f: did the trick. – CarpelTunnel Nov 15 '14 at 01:42

1 Answers1

0

You want to save the object using pickle, which represents an object as a string so that it can be saved. Here is sample code:

import pickle  # or import cPickle as pickle

# Create dictionary, list, etc.
favorite_color = { "lion": "yellow", "kitty": "red" }

# Write to file
f_myfile = open('myfile.pickle', 'wb')
pickle.dump(favorite_color, f_myfile)
f_myfile.close()

# Read from file
f_myfile = open('myfile.pickle', 'rb')
favorite_color = pickle.load(f_myfile)  # variables come out in the order you put them in
f_myfile.close()
Michael
  • 13,244
  • 23
  • 67
  • 115