Mike
Mike

Reputation: 507

converting part of a text file to list

I have a tab-delimited text file of movies and actors. The entries are in the following format:

The Shawshank Redemption    ["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"]

The Dark Knight ["Christian Bale", "Heath Ledger", "Aaron Eckhart", "Michael Caine"]

Is there a simple way to have python treat the actor "list" as a python list data structure, rather than a string with [ and ] characters? I've tried to write code to slice the string starting at the [ character, strip the [,], and " using .strip() and .rstrip(), then using .split(' ,') to make a list out of the remaining string. but that didn't return the results I wanted.

Upvotes: 2

Views: 67

Answers (1)

jayelm
jayelm

Reputation: 7677

Use ast.literal_eval, the safer version of python's eval() function, which takes a string input and treats it as python code. Assuming there's always one tab stop, you can split with tabs '\t' just evaluate the second element:

import ast
for line in f.readlines():
    temp_list = ast.literal_eval(line.split('/t')[1])
    # do something

Just a breakdown, using your first line as example:

>>> first_line = "The Shawshank Redemption    ["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"]"
>>> split_line = first_line.split('/t')
>>> split_line
['The Shawshank Redemption', '["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"]']
>>> best_list_ever = ast.literal_eval(split_line[1])
>>> best_list_ever
["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler"]

Upvotes: 2

Related Questions