[Tutor] search through a list
Brian van den Broek
bvande at po-box.mcgill.ca
Sun Jul 3 08:59:46 CEST 2005
nephish said unto the world upon 02/07/2005 23:41:
> hey there
> i have a file that i want to read.
> each line in the file is the name of a file.
> the next line is how many lines are in that file.
>
> example of loglist.txt
>
> log1.txt
> 232
> log2.txt
> 332
> log3.txt
> 223
>
> so log1 is a text file that has 232 lines in it.
>
> ok, so what i want to do is read this file, see if the file i am looking
> for is in it
> and if so, i need to know how many lines are in the file.
>
> here is what i have so far.
>
> import os
>
> #get a list of Logs in logs folder
> LogFiles = os.listdir('/home/nephish/Projects/Piv_GCI/logs')
>
> #open the loglist file and read the lines
> LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r')
> LogsRead = LogList.readlines()
>
> #see if there is a new log file.
> for i in LogFiles:
> if LogFiles[i] not in LogList:
> #if there is a new log, open it and read the lines
> StrName=(LogFiles[i])
> NewLog = open('/home/nephish/Projects/Piv_CGI/logs'+StrName,'r')
> NewLogRead=NewLog.readlines()
> #print the lines (testing only)
> for x in NewLogRead:
> print x
> print '\n'
> print '\n' #end for loop
> else: #if the log file is not new,
>
> um this is where i am stuck. i need search the LogList for the name of
> the name of the file in LogFiles and get the line number back so i can
> use it to compare with how many lines are in the log file so i can only
> process the data in the new lines ... does this make sense ?
>
> i need to find the item in a list, and when found, return the next line.
>
> any takers?
>
> thanks
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
It's late and I might not have completely understood the task. Warning
given:
So, you have a list of strings, and each is a line from your text file
described at the top, right?
If so, maybe this will meet your needs:
>>> l_list = ['these are\n', 'just some lines\n', 'to test with\n',
'nothing to see\n']
>>> def line_finder(line_list, flag):
flag = flag.strip()
return_next = False
for line in line_list:
if return_next:
return line.strip()
else:
if line.strip() == flag:
return_next = True
>>> line_finder(l_list, 'just some lines')
'to test with'
>>>
(If the line isn't found, the function returns None.)
HTH,
Brian vdB
More information about the Tutor
mailing list