[Tutor] Hello World in Python without space
Steven D'Aprano
steve at pearwood.info
Sat Jul 16 06:38:44 CEST 2011
Richard D. Moores wrote:
> But that makes me wonder if there isn't a simpler way to do it with
> Python -- to delete the contents of a file without deleting the file?
Opening a file for writing will flush the contents.
open(filename, 'w')
will do it, taking advantage of Python's garbage collector to
(eventually) close the file. The more careful way is hardly any harder:
open(filename, 'w').close()
and this ensures that the file isn't left open any longer than necessary.
--
Steven
More information about the Tutor
mailing list