File Handling Problem

SUBHABRATA BANERJEE subhakolkata1234 at gmail.com
Sat Sep 5 02:39:24 EDT 2009


Dear Sir,

Thank you for your kind reply. I would surely check your code. Meanwhile, I
solved it using readlines() but not in your way. I will definitely have a
look in your code. My solution came so smart that I felt I should not have
posted this question.

But I would like to know about,

i) Fileinput.
ii) Ast.
And one small question does Python has any increment operator like ++ in C.

Thank you for taking out the time to write answer for me.

Wishing you a happy day ahead,

Best Regards,
Subhabrata.

On Fri, Sep 4, 2009 at 8:43 PM, Lucas Prado Melo <lukepadawan at gmail.com>wrote:

>  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/20090905/9fdb8cf9/attachment.html>


More information about the Python-list mailing list