Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to import list from file in python

Tags:

python

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)]
like image 428
graph Avatar asked Dec 03 '25 16:12

graph


1 Answers

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))
like image 175
unutbu Avatar answered Dec 05 '25 06:12

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!