Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not recognizing list data as a list upon import

Tags:

python

import

Extremely simple but frustrating... I'm importing data that is already structured as a list, yet no matter what I try python keeps reading it in as a string.

How do I make ranks[] a proper list instead of a string? It seems like with how this data is formulated this should be near automatic, instead it's fighting me like crazy and making ranks[0] = "["

dataset:

['accounting', 5, 9, 11, 0, 0]
['polysci', 1, 2, 24, 0, 0]

script:

file = open("sub_ranks.txt","r+")
ranks = []
for line in file:
    ranks = line
    group = ranks[0]
    if ranks[1] >= 15:
        print group
        f = open("results.txt","a")
        f.write(group+"\n")
        f.close()
like image 613
some1 Avatar asked Feb 14 '23 01:02

some1


1 Answers

A better method would be to save your file in a different format, rather than saving in python syntax. Python gives you many "batteries included" for this - for example, you could use json, or write to a csv file, or perhaps use pickle if the data doesn't need to be human readable.

However, if you're just after a quick and dirty solution then literal eval can give you a list:

>>> import ast
>>> s = "['accounting', 5, 9, 11, 0, 0]"
>>> ast.literal_eval(s)
['accounting', 5, 9, 11, 0, 0]
like image 135
wim Avatar answered Mar 06 '23 02:03

wim