[Courses] [python] No lesson -- open discussion

Akkana Peck akkana at shallowsky.com
Sat Aug 27 03:38:19 UTC 2011


Leslie writes:
> I am trying to get good at manipulating files in python.  My next
> objective: to delete one line of a file.  From my researches on the web,
> it looks like you have to do it indirectly, by writing the lines you
> want to keep to a "good" file. Here is an example:
[ ... ]
>  Is this in fact the best way to get rid of a line? 

Yes. I don't know of any way to insert or delete lines inside files
under Linux (whether in Python or any other language).

Your example is exactly how I'd do it, with two exceptions. First,
there's no need to write the bad line to a second file unless you
need to save that as well. You can just say 
...     if not "goofy" in l:
...         goodf.write(l)
Of course, if the goal is to keep a record of the bad lines, then I'd
create a third file just as you did.

Second, instead of
>>> lines = inp.readlines()
>>> for l in lines:

I'd do
>>> for l in inp :

The difference is that the second version reads one line from the
file at a time, while the first reads the whole file in to a list,
so Python has to keep the contents of the whole file in memory.
Of course that's not a big deal for your small example file, but
if you wanted to use it on a really large file, it might make a
difference.

	...Akkana


More information about the Courses mailing list