如何读取包含产生的整数列表的输出行 [英] 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]
我想从该特定目录的所有文件中读取倒数第二行,并再次将其用作包含相同值的新python脚本中的列表.这样我就可以再次处理这些列表.
I would like to read this penultimate line from all the files from that specific directory, and using it again as a list in my new python script containing the same values, of course. So I will be able to process again these lists.
所有文本文件名以"chr"开头,以".txt"结尾
All the text filenames start by "chr" and finish by ".txt"
推荐答案
您可以使用以下命令-iglob
匹配文件名,literal_eval
将该数据解析为列表,使用deque
高效地获取文件的最后两行:
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
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'))
这篇关于如何读取包含产生的整数列表的输出行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!