如何从其他文件读取数组?

问题描述

我有一个文件(list.txt),具有这样的巨大数组:

['1458575','1458576','1458577','1458578'...]

我想在脚本中阅读它,但是输出为白色。目标是打印file.txt的行数(list.txt)

numbers_line = open("list.txt","r")
lines = numbers_line.readlines().split(',')
i=0
f=open('file.txt')
for line in f:
    if i in lines:
        print (line)
    i+=1

但是,如果我将数组直接放置就可以读取,但是考虑到这是一个巨大的数组,这可能没有帮助。

lines=['1458575','1458578','1458579','1458580','1458581','1458582','1458583','1458584']
i=0
f=open('file.txt')
for line in f:
    if i in lines:
        print (line)
    i+=1

感谢您的支持

解决方法

这可以工作

with open('file.txt') as file:
    content = file.read()
a = []
exec('a = ' + content)  # executes - a = ['1458575',...]

替代方法-将file.txt复制到新文件my_lists.py。 在my_lists.py文件的开头添加“ a =”并执行

from my_lists import a
,

使用with open() as :代替open()close(),因为当传统手册open()close()出现错误时,它会在发生错误时自动关闭与文件的连接。不。

lines=['1458575','1458576','1458577','1458578','1458579','1458580','1458581','1458582','1458583','1458584']
lines = [int(x) for x in lines] # convert to integers

fpath = "list.txt"

with open(fpath,"r") as f:
    for x in f:
        x = x.trim() # remove end of line character
        if int(x) in lines:
            print(x) 
,

readlines返回行列表,而不是字符串

readline将返回一个字符串,但是split(',')将给出一个不是int的字符串列表

尝试

import ast
text_file = open("list.txt","r")
lines = list(map(int,ast.literal_eval(text_file.read().strip())))
i=0
f=open('file.txt')
for line in f:
    if i in lines:
        print (line)
    i+=1