0

I have wrote a list in to a file, how can i get it back as old array list.

list looks like this

['82294', 'ABDUL', 'NAVAS', 'B', 'M', 'MSCS', 'CUKE', '30', 'Kasargod', 'CU', 'Kerala', 'Online', 'PG-QS-12', '15', 'June,', '2013', '12.00', 'Noon', '-', '02.00', 'PM\n', '29']

['82262', 'ABDUL', 'SHAFWAN', 'T', 'H', 'MSCS', 'CUKE', '30', 'Kasargod', 'CU', 'Kerala', 'Online', 'PG-QS-12', '15', 'June,', '2013', '12.00', 'Noon', '-', '02.00', 'PM\n', '29']

when i read the file, it does consider as a string list, for eg:

consider first list:

var[0][0] should be 82294 not '

i am a python noob,

3
  • 1
    Are you able to re-serialize the initial array using pickle? Commented Jul 10, 2013 at 18:55
  • Have you serialized or pickled the list before putting it in file or just copied and put it as it is in a file? Commented Jul 10, 2013 at 18:57
  • eval can achieve the goal though it is not safe. Re-serialize using pickle is a better choice. Commented Jul 10, 2013 at 18:59

3 Answers 3

1

You can read the file line by line. For each line you can then eval it, or use json.loads to unpack it.

Sign up to request clarification or add additional context in comments.

1 Comment

ast.literal_eval is better and safer.
0

Why couldn't you just do it by hand ? You'll need to either be sure of the safety of the string or adapt the list comprehension to your needs.

foo = "['4','8','15','16','23','42']"
bar = [token.strip("'") for token in foo[1:-1].split(',')]

Comments

0
firstline=File.readline()  #read one line
firstlist=eval(firstline)

now you got first list

['82294', 'ABDUL', 'NAVAS', 'B', 'M', 'MSCS', 'CUKE', '30', 'Kasargod', 'CU', 'Kerala', 'Online', 'PG-QS-12', '15', 'June,', '2013', '12.00', 'Noon', '-', '02.00', 'PM\n', '29']

by using a loop you can get all the list back

eval() is a function it will conver string to python expression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.