ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 15 Dec 2021 16:26:44 +0100import txt file contents to SageMath/Pythonhttps://ask.sagemath.org/question/60268/import-txt-file-contents-to-sagemathpython/I have a text file with contents like the following
[[1, 4], [2, 6], [5, 7]]
[[1, 4], [2, 7], [5, 8]]
I would like to import the contents to SageMath/Python, and assign L=[[[1, 4], [2, 6], [5, 7]], [[1, 4], [2, 7], [5, 8]]].
I tried to use the following
with open('somefile.txt', 'r') as fp:
L = [RDF(l.strip()) for l in fp.readlines()]
But there is some error: could not convert string to float: '[[1, 4], [2, 6], [5, 7]]'
How could I solve this problem? How to convert the values to integer (not float)? Thank you very much.Wed, 15 Dec 2021 09:40:10 +0100https://ask.sagemath.org/question/60268/import-txt-file-contents-to-sagemathpython/Answer by slelievre for <p>I have a text file with contents like the following</p>
<pre><code>[[1, 4], [2, 6], [5, 7]]
[[1, 4], [2, 7], [5, 8]]
</code></pre>
<p>I would like to import the contents to SageMath/Python, and assign L=[[[1, 4], [2, 6], [5, 7]], [[1, 4], [2, 7], [5, 8]]]. </p>
<p>I tried to use the following</p>
<pre><code>with open('somefile.txt', 'r') as fp:
L = [RDF(l.strip()) for l in fp.readlines()]
</code></pre>
<p>But there is some error: could not convert string to float: '[[1, 4], [2, 6], [5, 7]]'</p>
<p>How could I solve this problem? How to convert the values to integer (not float)? Thank you very much.</p>
https://ask.sagemath.org/question/60268/import-txt-file-contents-to-sagemathpython/?answer=60276#post-id-60276One way is to use `sage_eval` to evaluate a string as Sage code.
Running it on each line gives a list. Then make the list of those lists.
Using the example in the question:
sage: with open('somefile.txt', 'r') as fp:
....: L = [sage_eval(line) for line in fp.readlines() if line.strip()]
....:
sage: L
[[[1, 4], [2, 6], [5, 7]], [[1, 4], [2, 7], [5, 8]]]
The `if line.strip()` test is to ignore any empty lines in the file.Wed, 15 Dec 2021 16:26:44 +0100https://ask.sagemath.org/question/60268/import-txt-file-contents-to-sagemathpython/?answer=60276#post-id-60276