为了账号安全,请及时绑定邮箱和手机立即绑定

Python-同时读取文本文件中的3行

Python-同时读取文本文件中的3行

蝴蝶刀刀 2021-03-30 13:10:19
我有一个file.txt这样的样子。testings 1response 1-atime 32stestings 2response 2-atime 32stestings 3*blank*testings 4errortestings 5response 5-atime 26s和印刷品['testings 1', 'testings 2', 'testings 3', 'testings 4', 'testings 5']     ['response 1-a', 'response 2-a', 'response 5-a']['time 32s', 'time 20s', 'time 26s']所以it'sa simpel代码,我有,它会打开文件时,使用readlines()的关键字和外观testings,response并time再附加字符串到3名seperat名单。如图所示,file.txt有些testings x是*blank*或具有error而不是response。我的问题是我需要列表始终具有相同的长度。像这样: ['testings 1', 'testings 2', 'testings 3', 'testings 4', 'testings 5'] ['response 1-a', 'response 2-a', '*error*', '*error*', 'response 5-a'] ['time 32s', 'time 20s', '*error*', '*error*',  'time 26s']因此,我在考虑是否可能“同时读取3行”并有一个if语句,其中所有3行都需要具有正确的关键字(“为True”),否则*error*在响应中插入和保持长度正确的时间表。还是有更好的方法来保持3个清单的长度相同?test = []response = []time =[]with open("textfile.txt",'r') as txt_file:    for line in txt_file.readlines():        if ("testings") in line:            test.append(line.strip())            if ("response") in line:            response.append(line.strip())        if ("time") in line:            time.append(line.strip())print (response)print (test)print (time)
查看完整描述

3 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):

    "Collect data into fixed-length chunks or blocks"

    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"

    args = [iter(iterable)] * n

    return zip_longest(*args, fillvalue=fillvalue)


with open("textfile.txt",'r') as txt_file:

    for batch in grouper(txt.readlines, 3):

        if ("testings") in batch[0]:

            test.append(line.strip())

        else:

            test.append('error')

        if ("response") in batch[1]:

            response.append(line.strip())

        else:

            response.append('error')

        if ("time") in batch[2]:

            time.append(line.strip())

        else:

            time.append('error')

假设总是有相同顺序的行,并且该文件始终以三行的批次进行组织,即使那只是一个空行。由于实际上看起来您的输入文件在每3个组之间都有一个空白行,因此您可能需要更改grouper才能读取4个批次。


查看完整回答
反对 回复 2021-04-09
  • 3 回答
  • 0 关注
  • 366 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信