Python Forum
extracting data from a list in a file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: extracting data from a list in a file (/thread-15515.html)



extracting data from a list in a file - clarablanes - Jan-20-2019

good morning guys,

I am trying to extract the descriptor in bold in a list (the list is in a file):

This is the content of the file: training_set_sub.txt
[['Verapamil', 'COC1=C(OC)C=C(CCN©CCCC(C#N)(C©C)C2=CC(OC)=C(OC)C=C2)C=C1', 0, 71, '0', '13', '2', 6, 7.0, 0.46, 5.09, '1', '0.60', '5.888', -2.447620829090909, '-7.093', '0'], ['Norverapamil', 'COC1=CC=C(CCNCCCC(C#N)(C©C)C2=CC(OC)=C(OC)C=C2)C=C1OC', 0, 68, '1', '13', '2', 6, 7.0, 0.46, 5.14, '1', '3.06', '5.914', -3.918865, '-7.435', '0']]

What I am doing is:

file = open('training_set_sub.txt','r')
all = file.read().replace("'",'').split('], [')
b = str(all).split(',')
print (b)

for row in all:
    print (b[3])
but this way I obtain:
71
71
and I need to obtain
71
68

Could you help me, please?


RE: extracting data from a list in a file - snippsat - Jan-20-2019

It's a Python list save to text file,if have controlled how it saved it would be better to serialize to eg json,pickle.
Then is easy to get list back in original form.

Here one with ast.literal_eval a safer eval() then can get list back.
import ast

with open('list.txt') as f:
    mylist = ast.literal_eval(f.read())

print([i[3] for i in mylist])
Output:
[71, 68]



RE: extracting data from a list in a file - clarablanes - Jan-20-2019

Thank you!