First time here? Check out the FAQ!

Ask Your Question
2

import txt file contents to SageMath/Python

asked 3 years ago

lijr07 gravatar image

updated 3 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 3 years ago

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.

Preview: (hide)
link

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: 3 years ago

Seen: 499 times

Last updated: Dec 15 '21