0

Just have a colors.txt file with data:

[(216, 172, 185), (222, 180, 190), (231, 191, 202), (237, 197, 206), (236, 194, 204), (227, 184, 194), (230, 188, 200), (232, 192, 203), (237, 199, 210), (245, 207, 218), (245, 207, 218)]

now just try to read this in python as an array

f = open("colors.txt", "r")
data = f.read()
data2 = np.append(data)
f.close()

now want to print first value but I have an error

print(data2[0])

TypeError: _append_dispatcher() missing 1 required positional argument: 'values'

2
  • You aren't using np.append as specified by its docs. Why are you using it here? What's it supposed to be doing? Commented Jan 16, 2020 at 17:09
  • Where does that data come from? I strongly recommend using context managers to handle file objects. Commented Jan 16, 2020 at 20:53

3 Answers 3

2

The problem is that you are appending in string data from your file, when you really want a list. So use literal_eval to safely evaluate the data type:

import numpy as np
from ast import literal_eval

with open('colors.txt') as fh:
    data = literal_eval(fh.read())

# np.array can consume a list
arr = np.array(data)

array([[216, 172, 185],
       [222, 180, 190],
       [231, 191, 202],
       [237, 197, 206],
       [236, 194, 204],
       [227, 184, 194],
       [230, 188, 200],
       [232, 192, 203],
       [237, 199, 210],
       [245, 207, 218],
       [245, 207, 218]])

You also don't want to use np.append, since this takes two arguments, the array you are appending to and the data to append. You want to construct an array out of the data you have read from the file

Sign up to request clarification or add additional context in comments.

Comments

0

use eval method to read your text and append in empty array

import numpy

data1=[]
f = open("colors.txt", "r")
data = f.read()
f.close()

L = eval(data)
print(L)
data2 = numpy.append(data1,L)
print(data2[0])

1 Comment

add context/explenation to avoid bot flagging and removal. (From LQ-Posts Review).
0

You can use eval to evaluate the text representation back into a python type:

f = open("colors.txt", "r")
data = f.read()
data = eval(data)
data2 = np.append(data)
f.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.