[Tutor] Hello World in Python without space
Richard D. Moores
rdmoores at gmail.com
Sat Jul 16 06:54:23 CEST 2011
On Fri, Jul 15, 2011 at 21:38, Steven D'Aprano <steve at pearwood.info> wrote:
>
> 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.
open("C:/test/test.txt", 'w').close()
Good to know. Thanks, Steven.
Dick
More information about the Tutor
mailing list