Python在文本文件中查找行并将它和下两行添加到lis中

2024-05-14 00:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我有一个代码块,它允许我在记事本文件中找到一个精确的行,并将其添加到GTINlist。不过,我还想在下面加一行,下面也加一行。但是,我不想将文件的其余部分作为列表导入。 这是我目前的代码:

GTINlist=[]
GTIN=input("Please enter your GTIN code. ")
GTINcodes = [line for line in open('GTINcodes.txt') if GTIN in line]
stringGTINcode = str(GTINcodes)
GTINlist.append(stringGTINcode)*

Tags: 文件代码in列表inputyourlinecode
3条回答

在这种情况下,不能使用列表理解。但你可以这样做:

GTINlist=[]
GTIN=input("Please enter your GTIN code. ")
GTINcodes = []
read_ahead = 0
for line in open('GTINcodes.txt'):
    if GTIN in line:
        GTINcodes.append(line)
        read_ahead = 2
    elif read_ahead > 0:
        GTINcodes.append(line)
        read_ahead -= 1
stringGTINcode = str(GTINcodes)
GTINlist.append(stringGTINcode)*

以下是我所做的:

GTIN=input("Please enter your GTIN code. ")
with open('GTINcodes.txt', 'r') as file:
    GTINcodes = file.readlines()  #this seperates the lines of the file into the list called GTINcodes
GTINlist = GTINcodes[GTINcodes.index(GTIN):GTINcodes.index(GTIN) + 3]  #create the list GTINlist starting from the index where GTIN is found and add next two lines

内置的next()使迭代器前进一步。所以在你的情况下:

# setup
GTIN = input("Please enter your GTIN code. ")
GTINcodes = []


extra = 2  # number of extra lines to be appended

with open('GTINcodes.txt') as f:
    for line in f:
        if GTIN in line:
            GTINcodes.append(line)
            for _ in range(extra):
                GTINcodes.append(next(f))
            # if need to loop through the rest of the file, comment out break
            break

这可以通过使用itertools.dropwhile轻松跳过其中没有GTIN的行来进一步简化。dropwhile接受一个谓词和一个iterable,并返回一个迭代器,该迭代器从谓词为false的第一个值开始从iterable中生成值。所以:

^{pr2}$

相关问题 更多 >