Python does not recognize list data as a list when importing

Extremely simple, but disappointing ... I import data that is already structured as a list, but no matter what I try to use python, it reads it as a string.

How to make ranks [] a valid list instead of a string? It seems like with the wording of this data it should be almost automatic, instead he fights me like crazy and does the ranks [0] = "["

data set:

['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()
+4
source share
3 answers

, python. Python "", , json csv pickle, .

, , literal eval :

>>> import ast
>>> s = "['accounting', 5, 9, 11, 0, 0]"
>>> ast.literal_eval(s)
['accounting', 5, 9, 11, 0, 0]
+4

ranks=[] bject.

, ast.literal_eval , python, python.

from ast import literal_eval

with open("sub_ranks.txt", "r+") as f:

    for line in f:
       ranks = literal_eval(line)

- file Python2, . >

- with . , , .

+3

You open the file in text mode (default mode). Thus, all content is read as text. You have two options: parse the text data manually or use the "binary" mode and think about the logic of serialization.

The open () function flags are shown here: http://docs.python.org/2/library/functions.html#open

+1
source

All Articles