How do I cut parts from a text file

R

Rigga

Hi,

I am new to Python and need to parse a text file and cut parts out i.e. say
the text file contained 5 rows of text:

line 1 of the text file
line 2 of the text file
line 3 of the text file
line 4 of the text file
line 5 of the text file

And the text I want starts at line 2 and goes through to line 4, what is the
best way to cut this text out? I guess I need to mark the start and end of
the text and then pass these values to a command which will chop the file
at that location however I am at a loss.

Any advice or pointers of where to find more info would be greatly
appreciated.

Thanks

RiGGa
 
F

Fredrik Lundh

Rigga said:
I am new to Python and need to parse a text file and cut parts out i.e. say
the text file contained 5 rows of text:

line 1 of the text file
line 2 of the text file
line 3 of the text file
line 4 of the text file
line 5 of the text file

And the text I want starts at line 2 and goes through to line 4, what is the
best way to cut this text out?

the same way as you'd do it in any other programming language...

you can add stuff to the end of a file, but you cannot insert or remove stuff
inside the file, without rewriting the rest of the file. unless your files are really
huge, the easiest way to do this is to

1) load the entire file into memory

text = open(filename).readlines()

2) manipulate the data structure in memory

# remove first and last line
del text[0], text[-1]

3) write it back

f = open(outfilename, "w")
f.writelines(text)
f.close()

</F>
 

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

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top