How do I cut parts from a text file

Fredrik Lundh fredrik at pythonware.com
Tue Dec 21 17:40:56 EST 2004


"Rigga" <rigga at hasnomail.com> wrote:

> 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>







More information about the Python-list mailing list