Home > Software > Creating and Updating File Timestamps with Python’s Touch Command

Creating and Updating File Timestamps with Python’s Touch Command

Anastasios Antoniadis

Share on X (Twitter) Share on Facebook Share on Pinterest Share on LinkedInIn Unix-like operating systems, the touch command is commonly used to update the access and modification timestamps of a file to the current time. If the file does not exist, it is created with zero length. This functionality is not just limited to …

Python

In Unix-like operating systems, the touch command is commonly used to update the access and modification timestamps of a file to the current time. If the file does not exist, it is created with zero length. This functionality is not just limited to shell environments; Python provides similar capabilities through its standard library, offering a versatile way to emulate the touch command programmatically within Python scripts. This article explores how to create and update file timestamps using Python, akin to the Unix touch command, covering both built-in libraries and third-party packages.

Using the pathlib Module (Python 3.4+)

Introduced in Python 3.4, the pathlib module offers an object-oriented approach to filesystem paths. One of its many features is the Path.touch() method, which mimics the Unix touch command. This method updates the file’s timestamps or creates the file at the specified path if it does not exist.

Example:

from pathlib import Path

# Define the file path
file_path = Path('example.txt')

# Touch the file
file_path.touch(exist_ok=True)

print(f"File '{file_path}' has been touched.")

The exist_ok=True argument specifies that if the file already exists, the function should not raise an exception, merely updating the file’s timestamps. If exist_ok is set to False and the file exists, a FileExistsError will be thrown.

Using the os Module

For those who prefer or require a more traditional approach, Python’s os module provides functions to interact with the operating system, including modifying file timestamps through the os.utime() function.

Example:

import os
import time

# Define the file path
file_path = 'example.txt'

# Create the file if it doesn't exist
open(file_path, 'a').close()

# Update the file's timestamps
os.utime(file_path, (time.time(), time.time()))

print(f"File '{file_path}' has been touched.")

In this example, the file is first created with zero length if it doesn’t exist by opening it in append mode ('a') and immediately closing it. The os.utime() function is then used to update the access and modification times of the file to the current time, as returned by time.time().

Using Third-Party Libraries

While Python’s standard library provides robust tools for emulating the touch command, some may prefer the additional features or simplified syntax offered by third-party libraries. For file manipulation, libraries such as shutil or higher-level abstractions available through packages like pyfilesystem2 can be used, though for the specific task of touching files, the standard library is usually sufficient.

Conclusion

Python’s flexibility and comprehensive standard library allow for easy emulation of Unix-like commands, including touch, for file creation and timestamp updates. Whether you choose the object-oriented approach provided by pathlib or the more traditional os module, Python scripts can effectively manage file timestamps, facilitating tasks such as dependency checking, cache validation, or simply ensuring a file exists without modifying its contents. By leveraging these capabilities, Python developers can write more efficient and effective file manipulation code, integrating seamlessly with the underlying operating system’s features.

Anastasios Antoniadis
Follow me
Latest posts by Anastasios Antoniadis (see all)
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x