Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use write. For instance, the following will create the file /tmp/file.txt containing [1, 2, 3, 4, 5].

sage: L = [1,2,3,4,5]
sage: with open("/tmp/file.txt", "w") as f:
....:     f.write(str(L))
....:

Converting L to its string representation using str as above does not guarantee that you'll be able to reconstruct the object afterwards when you read the file. For instance, this is the case if you save a polynomial ring to a file. The solution is to use dumps that allows you to recover the object you are saving using loads:

sage: R.<x> = ZZ[]
sage: with open("/tmp/file2.txt", "w") as f:
....:     f.write(dumps(R))
....:

Then /tmp/file2.txt contains a strange-looking string (xœk`J.NLOÕ+ÊÌK/Ö+ÈÏ©ÌËÏÍLÌAbƃäâ“óóŠKŠJ“Kò‹¸àrA@)®BF dC2óJRÓS‹ÀÚ¸<!ˆ:&Í BæPÆ ¿Î’ B=) but you can load the polynomial ring that was saved afterwards:

sage: with open("/tmp/file2.txt") as f:
....:     S = loads(f.read())
....:
sage: S
Univariate Polynomial Ring in x over Integer Ring