How to read an output line containing a list of produced integers

In my penultimate line (next to the last) of all the files in a specific directory, I have a list of integers:

[142356, 12436546, 131434645, 56464]

I would like to read this penultimate line from all the files from this particular directory and use it again as a list in my new python script containing the same values, of course. Therefore, I can process these lists again.

All text file names begin with the symbol "chr" and end with ".txt"

0
source share
2 answers

: iglob literal_eval deque :

from collections import deque
from glob import iglob
import ast

def get_lists(pattern):
    for filename in iglob(pattern):
        with open(filename) as fin:
            penultimate = deque(fin, 2)[0]
            yield ast.literal_eval(penultimate)

data = list(get_lists('chr*.txt'))
+2

ast.literal_eval glob.glob:

import ast
import glob
print([ast.literal_eval(open(filename).readlines()[-1]) for filename in [("desired_directory/chr*.txt"])
+1

All Articles