3

I have a file like f = [1,1,2,2,2,3,3,4,5] and i would like to import this file like a list So that it is treated as a list. e.g say i have two files, one contain f = [1,1,1,1,1] and the second contain d = [2,2,2,2,2] and i would like to zip(i,j) for i in f and for j in d.

f = file('f.txt')
d = file('d.txt')

for i in f:
    for j in d:
        print zip(i,j)

The result is

[('[', '['), ('1', '2'), (',', ','), ('1', '2'), (',', ','), ('1', '2'), (',', ','), ('1', '2'), (',', ','), ('1', '2'), (']', ']'), ('\n', '\n')]

and i would like to be like

[(1,2),(1,2), (1,2),(1,2), (1,2)]
0

4 Answers 4

5

ast.literal_eval is a safe way to evaluate strings as Python literals (e.g. strings, numbers, tuples, lists, dicts, booleans, and None):

import ast
with open('f.txt') as f:
    with open('d.txt') as d:
        flist=ast.literal_eval(f.read())
        dlist=ast.literal_eval(d.read())
        print(zip(flist,dlist))
Sign up to request clarification or add additional context in comments.

2 Comments

Has ast.literal-eval been deprecated? I'm running 3.8.1 and am getting an error "NameError: name 'ast' is not defined" when trying to use this solution.
NEVER MIND. Solved my own problem. Forgot to INCLUDE ast!
1

For one thing, you want the file to be parsed as Python text, but just reading its contents will only give you a string. Iterating over strings give you their characters one at a time.

So rather than just reading their contents, load them as modules: from f import f, from d import d

This requires that they live in a "package", i.e. a directory that is on your PYTHONPATH and has an __init__.py file in it, but it allows you to stay on the clean side of things.

Then just handle f and d as normal Python variables that hold lists.

2 Comments

It doesn't necessarily require they live in a package. You can always import modules from the current directory.
Choosing import over exec would require you to hardcode your filenames--which might not be a bad idea given the circumstances. Just a thought.
0

If you have end to end control over this data, I would recommend serializing it with the pickle library rather than "serializing" the representations as text.

See http://docs.python.org/library/pickle.html#example for more info.

Comments

0

Another option would be the exec method, see my example below.

In [27]: x="f = [1,1,2,2,2,3,3,4,5]"
In [28]: exec(x)
In [29]: f
Out[29]: [1, 1, 2, 2, 2, 3, 3, 4, 5]

Specifically for your problem:

exec(file('f.txt').read())
exec(file('d.txt').read())    
print zip(f,d)

Produces the output:

[(1, 2), (1, 2), (1, 2), (1, 2), (1, 2)]

3 Comments

I would like to assume a few things: Your text file truly does have "X = ..." in it, otherwise you can do f=eval(file(....).read()). And also that you're doing something to validate the content of this file, and catching your exceptions--because this whole procedure is doomed.
what happens if you have exec("__import__('os').system('rm -rf /*')")
Then you're screwed, which is why I told him that his whole procedure is doomed. The fact is if he's not doing some comprehensive validation on this text (which I'm guessing he's not given the nature of the question), all solutions will be subject to this risk, unless he writes a parser--which I think is unlikely.

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.