猿问

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

我有一个file.txt这样的样子。


testings 1

response 1-a

time 32s


testings 2

response 2-a

time 32s


testings 3

*blank*


testings 4

error


testings 5

response 5-a

time 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)


蝴蝶刀刀
浏览 367回答 3
3回答

眼眸繁星

from itertools import zip_longestdef 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个批次。
随时随地看视频慕课网APP

相关分类

Python
我要回答