I’d like to create a file with path x using python. I’ve been using os.system(y) where y = 'touch %s' % (x). I’ve looked for a non-directory version of os.mkdir, but I haven’t been able to find anything. Is there a tool like this to create a file without opening it, or using system or popen/subprocess?
I’d like to create a file with path x using python. I’ve been using
Share
There is no way to create a file without opening itThere isos.mknod("newfile.txt")(but it requires root privileges on OSX). The system call to create a file is actuallyopen()with theO_CREATflag. So no matter how, you’ll always open the file.So the easiest way to simply create a file without truncating it in case it exists is this:
Actually you could omit the
.close()since the refcounting GC of CPython will close it immediately after theopen()statement finished – but it’s cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.In case you want
touch‘s behaviour (i.e. update the mtime in case the file exists):You could extend this to also create any directories in the path that do not exist: