搜索文件只能工作一次

时间:2015-04-13 09:32:47

标签: python arrays file python-2.7 loops

我有这段代码:

import linecache
car=1
vehical=[]
for x in range (7): #run this 7 times
    car=car+3 #number plates are on every 3rd line
    to_add=linecache.getline('finesV2.txt', car) #take the line (car variable contains integer concerning which one)
    vehical.append(to_add) #add this to array
file = open("details.txt", "r")
car=0
for x in range (7): #run this 7 times
    searchfor=vehical[car][0:7] #load time to search file for
    print "searchfor",searchfor #for debugging
    for line in file: #run amount of lines that are in the file
        if searchfor in line: #check if item being searched for is in that line
            print line #print out the line
    car=car+1 #increase the car variable to search for next item in vehicle array on next run
file.close()

该程序输出以下内容:

searchfor GX99QME
GX99QME,Alex 123,test street

searchfor IL45LTQ
searchfor ZX46GSR
searchfor GN11ILW
searchfor IN82SSD
searchfor WE50JEY
searchfor QS26DLO

然而,我想要并期望程序要搜索文件中的每个号牌以加载驱动程序详细信息。我已经确认搜索功能正在运行,并且我正在搜索的文件中的号牌是正确的,因为如果第14行更改为:

if "IL45LTQ" in line:

然后程序返回:

searchfor GX99QME
IL45LTQ,Tom

searchfor IL45LTQ
searchfor ZX46GSR
searchfor GN11ILW
searchfor IN82SSD
searchfor WE50JEY
searchfor QS26DLO

理想情况下,我想要的是返回所有车牌详情的程序。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

经过一些进一步的研究后发现,读取并没有跳回到开头,我不得不添加file.seek(0)将其重置回文件的顶部。