2

How can I load the following text file in Python which contains the points in the list within list form. The following contains the file is already in list form which python read as it is

The file is d0.txt

[(  0.,   0.,  5.) ( 10.,   0.,  5.) (  0.,  10.,  5.)]

Any suggestion and help is appreciated

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    Did you just dump the output of some `print` call to a `.txt` file? *Why*? You should take a minute to think about how you are serializing your data and then you won't have to roll your own parser every time... – juanpa.arrivillaga Sep 12 '17 at 17:16
  • Please have a look over this – deepakpawar.2310 Sep 12 '17 at 18:56
  • https://stackoverflow.com/questions/46183575/how-can-i-print-the-output-list-into-text-file – deepakpawar.2310 Sep 12 '17 at 18:56
  • You need to take a step back. Your questions are great examples of the [XY-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). That is, you keep asking "how do I do this" but you *really just want to serialize and deserialize a `numpy.ndarray`*. For that, you should use the [*built-in serialization format*](https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html). So all you want is `np.save(file_name, my_array)` and then to get it back, `my_array = np.load(file_name)`. – juanpa.arrivillaga Sep 12 '17 at 19:20
  • And **just as I suspected** you were simply dumping the string representation of your `numpy.ndarray` to a text file: `f.writelines ( str ( d ) + '\n' )` – juanpa.arrivillaga Sep 12 '17 at 19:20

1 Answers1

0

You could use ast.literal_eval:

import ast
data = ast.literal_eval(open('d0.txt').read())

I'm assuming you have a typo in the string (you're missing commas between tuples).

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • You are assuming too much. This looks like a dump of a `str` call on a structured `np.ndarray`. So try: `mytype = np.dtype([('a',np.float,), ('b', np.float,), ('c',np.float,)])` and then `print(np.array([( 0., 0., 5.), ( 10., 0., 5.), ( 0., 10., 5.)],dtype=mytype))` – juanpa.arrivillaga Sep 12 '17 at 17:24
  • Anyway, perhaps I was too quick to judge, but I saw high rep, but just checked and I guess you just recently started contributing regularly to the Python tag, but *given your assumption* you should have flagged this as a duplicate for [this well known target](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python) – juanpa.arrivillaga Sep 12 '17 at 17:27
  • yes under the assumption of course it works! Also I don't consider your answer false since what the OP posted is not valid python syntax. – coder Sep 12 '17 at 17:33
  • Please have a look over this – deepakpawar.2310 Sep 12 '17 at 18:56
  • https://stackoverflow.com/questions/46183575/how-can-i-print-the-output-list-into-text-file – deepakpawar.2310 Sep 12 '17 at 18:56