simple way to touch a file if it does not exist

bukzor workitharder at gmail.com
Wed May 21 20:56:38 EDT 2008


On May 21, 5:37 pm, Nikhil <mnik... at gmail.com> wrote:
> bukzor wrote:
> > On May 21, 5:10 pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote:
> >> On 22 Mag, 01:15, Nikhil <mnik... at gmail.com> wrote:
>
> >>> what are the simple ways?
> >>> I could think of os.open(), os.exec(touch file)
> >>> are there any simpler methods?
> >> Just use os.path.exists to check for file existence and open() as
> >> replacement for touch.
>
> >>>>> import os
> >>>>> if not os.path.exists('file'):
> >> ...     open('file', 'w').close()
> >> ...
>
> >> --- Giampaolohttp://code.google.com/p/pyftpdlib/
>
> > As simple as it gets is a single builtin function call:
>
> > open("somefile.txt", "a")
>
> > Leave out the ,"a" if you don't mind blanking a pre-existing file.
>
> Thanks :-)
>
> That reminds me to check if I could quickly nullify a file if it exists
>
> if os.path.exists('file'):
>         open('file', 'w').close()
>
> Right?

You only want to blank it if it exists? If it doesn't exist you won't
create it.
The .close() is superlative: since you don't keep the value, it gets
deallocated and closed by the destructor.



More information about the Python-list mailing list