Ask Your Question
2

import txt file contents to SageMath/Python

asked 2021-12-15 09:40:10 +0100

lijr07 gravatar image

updated 2021-12-15 09:40:56 +0100

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.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-15 16:26:44 +0100

slelievre gravatar image

One 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.

edit flag offensive delete link more

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: 2021-12-15 09:40:10 +0100

Seen: 458 times

Last updated: Dec 15 '21