目前我有一段代码,可以让我在记事本文件中找到一条确切的行并将其添加到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)*
答案 0 :(得分:0)
这是我做的:
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
答案 1 :(得分:0)
在这种情况下,您无法使用列表推导。但你可以这样做:
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)*
答案 2 :(得分:0)
内置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
接受谓词和迭代,并返回一个迭代器,该迭代器从谓词为false的第一个值开始,从迭代中产生值。所以:
from itertools import dropwhile
# setup
GTIN = input("Please enter your GTIN code. ")
lines_to_take = 3 # first line with GTIN in it, and 2 lines after it
lines = dropwhile(lambda line: GTIN not in line, open('GTINcodes.txt'))
GTINcodes = [next(lines) for _ in range(lines_to_take)]