File Handling Problem
Lucas Prado Melo
lukepadawan at gmail.com
Fri Sep 4 11:13:21 EDT 2009
On Fri, Sep 4, 2009 at 9:50 AM, joy99 <subhakolkata1234 at gmail.com> wrote:
> Dear Group,
>
> I have a file. The file has multiple lines. I want to get the line
> number of any one of the strings.
> Once I get that I like to increment the line number and see the string
> of the immediate next line or any following line as output. The
> problem as I see is nicely handled in list,
>
You could just grab each line and associate that line's content with its
line numbers, like this:
f = open("my_file.txt", "r")
line2pos = {}
for line_num, line in enumerate(f.readlines()):
if line not in line2pos:
line2pos[line] = []
line2pos[line].append(line_num)
(...)
This approach would be nice when you don't know which string to look for
beforehand.
In the case you already know it, there's no need for keeping the line2pos
variable, the right approach should be to iterate through the lines of the
file and, when you see the string you need, just display the next line and
exit:
def lookNextLineAfterString(s)
f = open("my_file.txt", "r")
found = False
while True:
line = f.readline()
if line == '':
break
line = line[:-1] #stripping the newline
if line == s:
found = True
break
if found == True:
nextString = f.readline()
if nextString == '':
print "String found but there's no next string"
else:
print "Next string is ", nextString[:-1]
else:
print "String not found"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090904/979dde88/attachment-0001.html>
More information about the Python-list
mailing list