Skip to content Skip to sidebar Skip to footer

How To Read An Output Line Containing A List Of Integers Produced

In my penultimate (next to last) line from all the files in a specific directory, I have a list of integers like this: [142356, 12436546, 131434645, 56464] I would like to read th

Solution 1:

You can use the following - iglob to match the filenames, literal_eval to parse the data as a list, and a deque to efficiently get the last two lines of a file:

from collections import deque
from glob import iglob
import ast

defget_lists(pattern):
    for filename in iglob(pattern):
        withopen(filename) as fin:
            penultimate = deque(fin, 2)[0]
            yield ast.literal_eval(penultimate)

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

Solution 2:

Using ast.literal_eval and glob.glob:

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

Post a Comment for "How To Read An Output Line Containing A List Of Integers Produced"