Ask Your Question
0

Save and retreive multiple dumps() items to/from file

asked 2023-04-04 19:58:44 +0200

brettpim gravatar image

I have written a backtrack search for objects in sagemath. I do not know how many it will find and I would like to write them to a file as I find them with

F.write(dumps(new_solution))

How can I read them all back in? Something like this solution in python. ​

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
0

answered 2023-04-07 04:02:19 +0200

I'm not sure if this is what you're trying to do:

sage: a = [2/3, 3/4, 5/6]
sage: for x in a:
....:     with open('results', 'wb') as F:
....:         F.write(dumps(a))
....: 
sage: with open('results', 'rb') as F:
....:     B = loads(F.read())
....: 
sage: B
[2/3, 3/4, 5/6]
edit flag offensive delete link more
0

answered 2023-04-05 21:03:29 +0200

brettpim gravatar image

updated 2023-04-05 21:22:54 +0200

I tried to use dumps() and loads() to do this in quite a few ways with no luck. I then decided to try it exactly as in the python solution that I link to in the question which works fine. Before the search I open a file for binary writing

f = open("results",'wb')

which is then passed to the search. When I find a solution in the backtrack search I simply call

pickle.dump(new_solution,f)

and then close the file when the search is complete.

To read everything back in I have

f = open("results", "rb")
results = []
try:
    while(True):
        result = pickle.load(f)
        results.append(temp)
except EOFError:
    print("end of file reached")
edit flag offensive delete link more

Comments

If anyone knows how to do this with sagemath's dums() and loads() please add another answer

brettpim gravatar imagebrettpim ( 2023-04-05 22:26:00 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-04-04 19:58:44 +0200

Seen: 332 times

Last updated: Apr 07 '23