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()
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With