-1

I've spent a few hours staring at this and I can't figure it out. I'm sure it's basic but would be great of you could kindly help me out.

I have a list named "export_data" that contains other lists, and integers. For example.

print(type(export_data[0]))
print(type(export_data[5]))

#Output is: <class 'list'>
<class 'int'>

I then write the "export_data" to a csv file. However, When I subsequently read the file and extract a column value it comes back as a string. So now I have a "[1,2,3]" that I'm unsure how to convert back to a list.

with open('record ' + str(current) + '.csv', 'a', newline='') as f:
    writer = csv.writer(f)

    writer.writerow(export_data)
    del writer
    f.close()

with open('record Wednesday,Apr:29.csv', 'r') as rf:
    reader = csv.reader(rf)
    for i in reader:
        (group_a.append(i[1]))
        (x.append(i[0]))
        (hr.append(i[5]))

print(type(export_data[0]))
print(type(export_data[5]))
#Output: <class 'str'>
<class 'str'>

I'm using the data from the csv file to plot the data in DASH using plotly. Therefore I can't enter a list for my x and y values. Thanks for your help.

1 Answers1

0

To convert "[1,2,3]" back to a list use eval() or ast.literal_eval as Patrick Artner mentioned (Note: eval is not a good practice and it's not safe, see comments. Still I use it in quick local scripting if I'm certain that the input data is safe) :

lst_str = eval("[1,2,3]")
print(lst_str)
print(type(lst_str))

===

import ast

lst_str = ast.literal_eval("[1,2,3]")
print(lst_str)
print(type(lst_str))

Output:

[1, 2, 3]
<class 'list'>
Thaer A
  • 1,570
  • 1
  • 5
  • 10