views:

202

answers:

4

I'm writing a function and I want it to touch a file so that I can write to that file. If the file doesn't exist, I will get an error. How can I say that?

+9  A: 

Just open the file for writing and it will be created if it doesn't exist (assuming you have proper permission to write to that location).

f = open('some_file_that_might_not_exist.txt', 'w')
f.write(data)

You will get an IOError if you can't open the file for writing.

awesomo
Yes. It's so simple.
old Ixfoxleigh
A: 

if you actually want to raise an error if the file doesn't exist, you can use

import os
if not os.access('file'):
    #raise error
f = open('file')
#etc.
Ant
I will definitely eventually use this. Thank you.
old Ixfoxleigh
Note that the file might become inaccessible between the call to `os.access` and the call to `open`.
Brian
Tim McNamara
@Tim McNamara: It's always better, as it can always happen no matter how many checks you do beforehand.
sdolan
A: 
f = open('tzzzz.txt', 'rw') # or r+
f.truncate(0) # empty file

it's not the best solution but depend of what you want the best thing is to use try except ; Better Ask Forgiveness than Permission

singularity
+1  A: 

Per the docs, os.utime() will function similar to touch if you give it None as the time argument, for example:

os.utime("test_file", None)

When I tested this (on Linux and later Windows), I found that test_file had to already exist. YMMV on other OS's.

Of course, this doesn't really address writing to the file. As other answers have said, you usually want open for that and try ... except for catching exceptions when the file does not exist.

GreenMatt