Implement touch using Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The Unix touch command creates a file if it does not exist, or updates its access and modification timestamps if it does. In Python, pathlib.Path.touch() (Python 3.4+) is the most direct equivalent. For older code, open(path, 'a').close() creates the file and os.utime() updates timestamps. You can also set specific timestamps using os.utime(path, (atime, mtime)). These approaches cover the three core use cases: creating empty files, updating timestamps to "now," and setting timestamps to specific values.
pathlib.Path.touch() (Recommended)
Path.touch() is the Pythonic equivalent of the touch command. With exist_ok=True (the default), it silently updates timestamps on existing files or creates new empty files.
os Module Approach
Using open(path, 'a').close() with append mode ensures existing file content is not overwritten. The 'w' mode would truncate the file, destroying its contents.
Setting Specific Timestamps
os.utime(path, (atime, mtime)) sets specific timestamps. Pass None instead of the tuple to set both timestamps to the current time. This matches touch -t in Unix.
Full touch Implementation
Batch Touch with Glob Patterns
Context Manager for Safe File Creation
Comparing Approaches
Common Pitfalls
- Using
'w'mode instead of'a':open(path, 'w').close()truncates the file to zero bytes, destroying its contents. Always use'a'(append) mode when mimickingtouchto preserve existing file content. - Not closing the file handle:
open(path, 'a')without.close()leaks a file descriptor. Useopen(path, 'a').close()or awithstatement. In CPython the garbage collector closes it eventually, but other implementations (PyPy) may not. - Parent directory does not exist:
Path("a/b/c.txt").touch()raisesFileNotFoundErrorifa/b/does not exist. Callpath.parent.mkdir(parents=True, exist_ok=True)first to create intermediate directories. - Permission errors on existing files:
Path.touch()attempts to open the file for writing to update timestamps. If the file is read-only or owned by another user, this raisesPermissionError. Useos.utime()which only requires ownership of the file, not write permission. - Race conditions with existence checks: Checking
if not path.exists()then creating the file is not atomic — another process could create or delete the file between the check and the action. UsePath.touch(exist_ok=True)which handles this atomically.
Summary
- Use
Path("file.txt").touch()for the simplest Pythonic equivalent of Unixtouch - Use
open(path, 'a').close()for Python 2 compatibility (never use'w'mode) - Use
os.utime(path, (atime, mtime))to set specific timestamps - Create parent directories with
path.parent.mkdir(parents=True, exist_ok=True)before touching nested paths - For batch operations, combine
Path.glob()with.touch()to update multiple files
Related reading
- Implementing a depth-first tree iterator in Python
- Implementing custom loss function in scikit learn
- Implementing Gradient Descent In Python and receiving an overflow error
- Implementing non-blocking remote logging handler
- Implementing PCA with Numpy
- Implementing ROC Curves for K-NN machine learning algorithm using python and Scikit Learn
- Implementing Stack with Python
- Import a module from a relative path
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.