【问题标题】:Searching file only working once搜索文件只工作一次
【发布时间】:2015-06-18 13:42:30
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

    标签: python arrays file python-2.7 loops


    【解决方案1】:

    经过进一步研究,结果表明 read 并没有跳回到开头,我不得不添加 file.seek(0) 以将其重置回文件顶部。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多