简体   繁体   English

如何从python中的文件导入列表

[英]how to import list from file in 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. 我有一个像f = [1,1,2,2,2,3,3,4,5]的文件,我f = [1,1,2,2,2,3,3,4,5]列表一样导入此文件,以便将其视为列表。 eg 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 = [1,1,1,1,1] ,第二个包含d = [2,2,2,2,2] ,我想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)]

ast.literal_eval is a safe way to evaluate strings as Python literals (eg strings, numbers, tuples, lists, dicts, booleans, and None): ast.literal_eval是将字符串评估为Python文字的安全方法(例如,字符串,数字,元组,列表,字典,布尔值和无):

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))

For one thing, you want the file to be parsed as Python text, but just reading its contents will only give you a string. 一方面,您希望将文件解析为Python文本,但是仅读取其内容只会给您一个字符串。 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 因此,不只是读取它们的内容,而是将它们作为模块加载: from f import ffrom d import d

This requires that they live in a "package", ie 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. 这要求它们位于“包”中,即位于您的PYTHONPATH上的目录,并且其中具有__init__.py文件,但是它使您无动于衷。

Then just handle f and d as normal Python variables that hold lists. 然后只需将fd当作持有列表的普通Python变量处理即可。

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. 如果您具有对这些数据的端到端控制,我建议您使用pickle库将其序列化,而不是将表示形式“序列化”为文本。

See http://docs.python.org/library/pickle.html#example for more info. 有关更多信息,请参见http://docs.python.org/library/pickle.html#example

Another option would be the exec method, see my example below. 另一个方法是exec方法,请参见下面的示例。

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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM