Question

I want to read from a .txt file, which has data saved as in list format.

['http://www.example.com/?date=20080301',
 'http://www.example.com/?date=20080302',
 'http://www.example.com/?date=20080303']

I have the following code:

with open("test.txt", 'r') as file_name:
    for urls in file_name:
        for url in eval(urls):
            print url

It worked well with exactly idential file (only different links) and now out of a sudden, it raises an exception:

File "<string>", line 1
    ['http://www.example.com/?date=20080301',
                                            ^
SyntaxError: unexpected EOF while parsing

Do you have any ideas?

Was it helpful?

Solution

Use ast.literal_eval():

import ast
with open("test.txt", 'r') as file_name:
    lists = ast.literal_eval(file_name.read())
    for url in lists:
        print url

It's much more efficient than using eval because, and quoting from the docs, it "safely evaluate[s] an expression node or a string containing a Python expression."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top