Ask Your Question
1

load contents of a .txt file into a Sage worksheet

asked 2016-09-24 18:40:15 +0100

barrybr gravatar image

updated 2016-09-26 02:09:38 +0100

I am on a Mac with OS 10.11.6, and I'm learning the notebook interface for Sage 7.2. As a start, in a Sage worksheet I created a .txt file containing the string "[1, 2, 3]" and saved it. I can open the text file directly and verify its contents just by clicking on it, but I can't yet do this in Sage. I'd like to be able to open it and convert the string to a usable Sage object. I'd appreciate explicit instructions, assuming nothing at all about my Sage background. Thank you.

Edit: In Mathematica for example I can write 'stream=OpenWrite["filename"];Write[stream,{89}];Close[stream]', execute; Mathematica says "filename". Then suppose I close Mathematica, shut off my Mac, re-open my Mac and Mathematica again, open a fresh notebook, write "stream2=OpenRead["filename"];list=ReadList[stream2];Close[stream2];list". If I do all that, Mathematica will say "{{89}}}". This is usable. If I next do "list[[1,1]]+ 1", Mathematica will say "90". I want to do the same kind of thing in Sage.

Remark: if in my particular environment I try the example in the Sage documentation in the section 'Saving and Loading Individual Objects': "A = MatrixSpace(QQ,3)(range (9))^2;A" --Sage returns the matrix and "save(A, 'A')" returns a hot link to A.sobj . If I then quit Sage and restart it, the next suggested command, "A = load('A')" evokes an error message:Traceback (most recent call last): File "<stdin>", line 1, in <module> File "_sage_input_3.py", line 10, in <module> exec compile(u'open("___code___.py","w").write("# -- coding: utf-8 --\n" + _support_.preparse_worksheet_cell(base64.b64decode("QSA9IGxvYWQoJ0EnKQ=="),globals())+"\n"); execfile(os.path.abspath("___code___.py")) File "", line 1, in <module>

File "/private/var/folders/7n/t9k4hfyn44s2qp7wxt479kn80000gn/T/tmpMnKw2r/___code___.py", line 2, in <module> exec compile(u"A = load('A')" + '\n', '', 'single') File "", line 1, in <module>

File "sage/structure/sage_object.pyx", line 1032, in sage.structure.sage_object.load (build/cythonized/sage/structure/sage_object.c:11594) IOError: [Errno 2] No such file or directory: 'A.sobj' Remark 2: I replicated this error on a Mac laptop using Sage 6.8 and OS 10.10.2.

edit retag flag offensive close merge delete

Comments

kcrisman gravatar imagekcrisman ( 2016-09-24 21:58:34 +0100 )edit

3 Answers

Sort by » oldest newest most voted
2

answered 2016-09-24 18:49:43 +0100

tmonteil gravatar image

updated 2016-09-24 18:50:26 +0100

You can do the following:

  • rename your file with the .sage extension, say my_file.sage
  • in this file, instead of just [1, 2, 3] you should give a name to your object, for example a=[1, 2, 3]
  • then, from your notebook, you can type load('/path/to/my_file.sage'), and you will be able to access the Python variable a.
edit flag offensive delete link more

Comments

Thanks, but I should have emphasized more strongly the extent of my ignorance.

Now I'm in the same situation, only with a .py file. I can see it in the .sage directory. I can click on it, and I get this:

This file was autogenerated from the file /Users/barrybrent/.sage/sage_notebook.sagenb/home/__store__/2/21/212/2123/admin/19/data/tesfile.sage

from sage.all_cmdline import * # import sage library _sage_const_89 = Integer(89) [_sage_const_89 ]

(because I saved [89] instead of [1, 2, 3]...)

but I still don't know how to load it within a worksheet. If I do this:

load('/Users/barrybrent/.sage/sage_notebook.sagenb/home/admin/19/data/tesfile\ .sage.py')

it's true that I don't get an error message, but I don't know how to access the [89] object from tesfile.sage within the worksheet.

barrybr gravatar imagebarrybr ( 2016-09-24 20:36:59 +0100 )edit
2

answered 2016-09-27 17:56:50 +0100

barrybr gravatar image

updated 2016-09-28 12:33:31 +0100

kcrisman gravatar image

I found an answer in Finch's book. First a quote:

“We used a module called os from the Python standard library module to help us write code that can run on multiple platforms. A text file must have a special character to denote the end of each line in the file. Unfortunately, for historical reasons, each family of operating systems (Mac, Windows, and UNIX) uses a different end-of-line character. The os module has a constant called linesep that contains the correct character for the platform that the code is run on. We used the statement import os to make the module available, and accessed the constant using the syntax os.linesep. We also used the function os.path.join to join the path to the file name with the correct character for the current operating system.”

Excerpt From: Craig Finch. “Sage Beginner's Guide.”

Example using a file named "File2.txt" containing a single text character, '1':

import os
path='/Users/barrybrent/.sage/sage_notebook.sagenb/home/__store__/2/21/212/2123/admin/19/data/'
fileName='File2.txt'
times = []
text_file = open(os.path.join(path, fileName), 'r')
line = text_file.readline()

(Comment: is just a character string. To convert it a Sage object useful in computations:)

elements=line.split(',')
times.append(float(elements[0].strip()))

(Comment: evaluate:)

times[0]

(Comment: Sage says"1.0". Now can we do arithmetic with times[0]?)

times[0]+1

Sage says "2.0"

edit flag offensive delete link more

Comments

I still am not 100% sure what you are trying to do, but I am very glad you found a solution that others can use! Finch's book is useful because it answers his questions about how to use Sage, not the ones that long-time heavy users ask.

kcrisman gravatar imagekcrisman ( 2016-09-28 12:34:26 +0100 )edit
1

answered 2016-09-24 21:57:56 +0100

kcrisman gravatar image

updated 2016-09-25 03:16:23 +0100

There is a better option. If you are using sagenb, which appears to be the case, then note that "Upload" supports the following:

Supported file formats: ... .html or .txt - a worksheet text file with html code and cells surrounded by {{{ and }}} that defines a worksheet

So if you put {{{ and }}} around some stuff in this fashion

{{{
a=[1,2,3]
///
}}}

you should get a proper (more or less) worksheet, which you can evaluate and then continue using a.

edit flag offensive delete link more

Comments

The .sage directory (where the file is) was originally hidden my Mac. I unhid it. But it remains hidden when using the Upload button in Sage. So the only way I know to navigate to it via Upload is to make a copy and place the copy somewhere that is visible to the Upload navigation window. (Please comment on this issue.) Then, when I do Upload on this copy, I see the original contents as printed above ("This file was autogenerated", etc.) At that point it's not clear to me how to access the contents (my list [89] as above) as a usable Sage object. I understand you to say I should do {{{; command;///;}} for some command. But: say I want to to add the file's contents to [7]. How do I refer to it without just doing "[89] + [7]"? Thanks.

barrybr gravatar imagebarrybr ( 2016-09-24 23:58:59 +0100 )edit

I looked back at my worksheet, somehow the scales dropped from my eyes, and I see now that the drop-down menu under "Data.." allows me to upload my .py file without the trickery I just described. But the rest of my question is still puzzling me: how to access the [89] in the file. I don't know where I should be wrapping some command in the triple braces, or what command is appropriate. Thanks.

barrybr gravatar imagebarrybr ( 2016-09-25 00:08:00 +0100 )edit

I'm sorry, I still don't quite understand what you are trying to do :( Trying to update answer.

kcrisman gravatar imagekcrisman ( 2016-09-25 03:16:04 +0100 )edit

Sorry--I'll try again. In Mathematica for example I can write 'stream=OpenWrite["filename"];Write[stream,{89}];Close[stream]', execute; Mathematica says "filename". Then suppose I close Mathematica, shut off my Mac, re-open my Mac and Mathematica again, open a fresh notebook, write "stream2=OpenRead["filename"];list=ReadList[stream2];Close[stream2];list". If I do all that, Mathematica will say "{{89}}}". This is usable. If I next do "list[[1,1]]+ 1", Mathematica will say "90". I want to do the same kind of thing in Sage.

barrybr gravatar imagebarrybr ( 2016-09-25 03:54:00 +0100 )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: 2016-09-24 18:40:15 +0100

Seen: 5,810 times

Last updated: Sep 28 '16