我正在用文本文档中的行填充列表。文本文档是一个日志文件,包含108行(条目),重复几百次。
我正在使用For循环来填充列表,但是我只需要前65行。有没有办法让For循环跳过第66-108行?我正在考虑使用下面的代码中显示的continue,使用我希望跳过的行号的模数。有没有办法在范围内使用'if modulo',或者我是否需要为每一行我都要跳过“if modulo”语句?
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
if loopcount % range(66,108) == 0: #
loopcount += 1
continue
loopcount += 1
data.append(line)
file = open('test.txt')
lines = file.readlines()
data = list()
loopcount = 0
for line in lines:
if loopcount % 108 < 65:
data.append(line)
loopcount += 1
试试这个:
next_loop = False
file = open('test.txt')
lines = file.readlines()
data = list()
for line in lines:
not_read = range(66,108)
#test every num in the list
for i in not_read:
if loopcount % i == 0:
loopcount += 1
next_loop = True
break
if next_loop:
next_loop = False
continue
loopcount += 1
data.append(line)