To create an empty csv file using with open, pass in the name of the new file and 'w' as second argument to make the file writable. If the file name is non-existing a new csv file is created. If the file exists, the content will be replaced. To prevent this from happening pass in 'a' to append the content to the file.
touch() function, creating a file at this provided path. To create a file using the command line in Python, use the pathlib module's Path. touch() function. If the mode argument is provided, then it is combined with the process' umask value to define the file mode and access flags.
There is no way to create a file without opening it There is os.mknod("newfile.txt")
(but it requires root privileges on OSX). The system call to create a file is actually open()
with the O_CREAT
flag. 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:
open(x, 'a').close()
Actually you could omit the .close()
since the refcounting GC of CPython will close it immediately after the open()
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):
import os
def touch(path):
with open(path, 'a'):
os.utime(path, None)
You could extend this to also create any directories in the path that do not exist:
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt")
. The only drawback is that this call requires root privileges on OSX.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With