Explain Codes LogoExplain Codes Logo

Implement touch using Python?

python
file-handling
permissions
timestamps
Anton ShumikhinbyAnton Shumikhin·Aug 26, 2024
TLDR

To emulate Unix's touch in Python, leverage the 'a' append mode when using open(). The code below creates newfile.txt if it doesn't exist without adding any content:

with open('newfile.txt', 'a'): pass

Brief and to the point - Voila! who said creating files should be a hard task?

Dive into basic file touch

Still breathing easy after the fast answer? Good, because things are about to get more fun! Instead of the basic open(), you can use Path.touch() from Python's pathlib module (Available in version 3.4+):

from pathlib import Path Path('newfile.txt').touch()

Not only does it create the file if it's not existing, it "high-fives" it (updates its modification time) if it already does.

Fancy attributes - file timestamps

Want to look under the hood and tinker with the file's attributes? Python's os.utime() is your go-to function. It allows us to modify a file's access and modification times without changing its content, like a ninja:

import os from pathlib import Path file_path = 'existing_file.txt' Path(file_path).touch() # Create the file if it doesn't exist # Modify access and modification times to current time (your time machine is here) os.utime(file_path, None)

Though armed with this mighty power, one must be wary of race conditions when using os.utime(). Fear not, our hero os module won't let you down, for it has the power to handle such conditions like a seasoned warrior.

Deep dive into file handling

As we take a deep dive into the realm of file handling, we stumble upon permissions and race conditions. Fear not, we are prepared for this adventure!

Permission magic

No sorcery here, just Python offering control over file permissions at creation time, using os.open, os.O_CREAT, and the mode parameter:

import os file_path = 'newfile_with_perms.txt' flags = os.O_CREAT | os.O_WRONLY mode = 0o640 # This permission level is so "640", it's essentially "read and write" for the owner file_handle = os.open(file_path, flags, mode) os.close(file_handle)

Attribute juggling

For times when you want a tight grip on file attributes, Python's os module is your best bet. Think of it as extreme file attribute aerobics `o_o`; you get to dictate the set attributes:

import os file_path = 'special_attributes_file.txt' if not os.path.exists(file_path): open(file_path, 'a').close() # Changing access and modification times (time-travel, anyone?) timestamp = (access_time, modification_time) os.utime(file_path, timestamp)

Cross-platform consistency

We love Python for its chameleon-like ability to adapt across platforms. Its standard library is a treasure chest of functions that help ensure your code runs smoothly, regardless of the OS. In creating a touch utility with Python, this cross-platform solution is essential.