File Handling Problem

J

joy99

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,

like list_one=["god","earth","sky","cloud","rain"]
list_one[0]="god"
list_one[2]="sky"

but can it be for string and file?

I can generally put a cursor and move it back and forth for my need
using index/find and then re. But, I was looking to use some built-in
methods. Can I use fileinput or ast? But, I was not finding any good
resources, using http://docs.python.org/library/fileinput.html#fileinput.input,
etc. did not help much.

If any one can kindly help me out.

Best Regards,
Subhabrata.
 
R

Rami Chowdhury

f = open("myfile.txt", "r")
list_one = f.read().splitlines()
f.close()

Or use f.readlines(), which would do the same thing IIRC?

joy99 said:
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,

like list_one=["god","earth","sky","cloud","rain"]
list_one[0]="god"
list_one[2]="sky"

but can it be for string and file?

It's easy to read a file into a list.

f = open("myfile.txt", "r")
list_one = f.read().splitlines()
f.close()
 
R

Rami Chowdhury

No: readlines () retains the "\n"s; splitlines () loses them

Ah, thank you for the clarification!
 
C

Chris Rebert

On Fri, Sep 4, 2009 at 11:39 PM, SUBHABRATA
BANERJEE said:
And one small question does Python has any increment operator like ++ in C.

No. We do x += 1 instead.

Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top