simple way to touch a file if it does not exist

N

Nikhil

what are the simple ways?
I could think of os.open(), os.exec(touch file)

are there any simpler methods?
 
B

bukzor

Just use os.path.exists to check for file existence and open() as
replacement for touch.


... 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.
 
N

Nikhil

bukzor said:
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?
 
B

bukzor

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.
 
M

Marc 'BlackJack' Rintsch

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.

The language neither guarantees *when* an object will be deallocated nor
that its destructor is called *at all*. It's cleaner to explicitly close
the file.

Ciao,
Marc 'BlackJack' Rintsch
 
B

bukzor

The language neither guarantees *when* an object will be deallocated nor
that its destructor is called *at all*. It's cleaner to explicitly close
the file.

Ciao,
Marc 'BlackJack' Rintsch

Good to know.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top