Search code examples
pythonarraysfileiterationline

How to read array from other file?


I have a file (list.txt) with huge array like this:

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

I want to read it in my script but the output is white. The goal is print the number of line (list.txt) of the file.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

However, if I put the array direct it's read, but considering that is a huge array this is not could be helpful.

lines=['1458575', '1458576', '1458577', '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

Thanks for your support


Solution

  • readlines returns list of lines, not string

    readline will return a string, but split(',') would give a list of string not int

    try this

    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