Create empty file using python
Create an empty file in a flash with open('filename', 'a').close()
. The 'a'
mode assures the file is born if it's not already there, and untouched like a painting in a museum if it does:
This one-liner is sports car of file handling. It's swift, safe, and doesn't need a pit crew for exception handling.
Crafting non-existing directories
A file needs a home. Use os.makedirs()
to build its abode when the directory order seems like chaos:
The exist_ok=True
flag makes os.makedirs()
all calms and composed if the directory already exists. No drama!
Keep time, Beat time
Need an alibi that a file was accessed now, or create it if it didn't exist? open()
and os.utime()
will back your story:
This chronomantic move updates the timestamp of a file, bringing it into existence if it didn't exist at all, without altering its quantum state (read: content).
Gratuitous closing: It's cleaner
In the realm of file handling, closing the door behind you is the haute couture. The with
statement is your personal stylist:
The with
block lets you skip the .close()
call because Python's context manager runs a classy exit for you.
File creation across realities (OS platforms)
Creating files in different realities — I mean, operating systems — can be as tricky as quantum mechanics, especially with laws of permissions. Stick to open()
, unless you have root privileges and the desire to tangle with os.mknod()
on OSX.
Stick with open()
. It's like your constant in a world (OS) of variables.
Guarding existing files
Actual files are more like Schrodinger's cats: you might or might not overwrite them. Use 'a'
mode to keep the cat alive:
The 'a'
mode ensures that if important_data.txt
exists, you won't annihilate it.
Unix's gift: Using touch method
The Unix touch
command can be borrowed by Python for file creation. Agreed, it's more of a Unix idiom, but Python is a language of appropriation:
Remember, this method is more like the Dark Arts. You can use it, but better to avoid due to portability and security concerns.
Was this article helpful?