I have a file named a.txt which looks like this:
I'm the first line
I'm the second line.
There may be more lines here.I'm below an empty line.
I'm a line.
More lines here.
Now, I want to remove the contents above the empty line(including the empty line itself). How could I do this in a Pythonic way?
You could do a little something like this:
and that makes the job much simpler.
The fileinput module (from the standard library) is convenient for this kind of thing. It sets things up so you can act as though your are editing the file "in-place":
Any idea how big the file is going to be?
You could read the file into memory:
which will read the file line by line and store those lines in a list (lines).
Then, close the file and reopen with 'w':
This will overwrite the current file. Then you can pick and choose which lines from the list you want to write back in. Probably not a very good idea if the file gets to large though, since the entire file has to reside in memory. But, it doesn't require that you create a second file to dump your output.
Basically you can't delete stuff from the beginning of a file, so you will have to write to a new file.
I think the pythonic way looks like this:
Here are some simpler versions of this, without
with
for older Python versions:and a very straight forward version that simply splits the file at the empty line:
Note that this can be pretty fragile, for example windows often uses
\r\n
as a single linebreak, so a empty line would be\r\n\r\n
instead. But often you know the format of the file uses one kind of linebreaks only, so this could be fine.Naive approach by iterating over the lines in the file one by one top to bottom: