How to touch a file in Python (like Unix touch)
Codemia Knowledge Hub ·
Use pathlib.Path("file.txt").touch() (Python 3.4+). Like Unix touch, it creates the file if it does not exist and updates its access and modification timestamps if it does. In older code, open(path, 'a').close() creates the file and os.utime() updates timestamps; os.utime(path, (atime, mtime)) sets specific values.
pathlib.Path.touch()
With exist_ok=True (the default), touch() silently updates timestamps on existing files or creates new empty ones.
Using the os module
Append mode ('a') never overwrites existing content. open(path, 'w').close() would truncate the file to zero bytes, so never use 'w' to mimic touch.
Close the handle, either with .close() or a with statement. open(path, 'a') on its own leaks a file descriptor; CPython's garbage collector closes it eventually, but other implementations (PyPy) may not.
Setting specific timestamps
os.utime(path, (atime, mtime)) sets specific timestamps, which matches touch -t in Unix. Pass None instead of the tuple to set both to the current time.
A fuller touch function
This version creates parent directories, supports touch -c (do not create), and accepts explicit times:
Parent directories matter: Path("a/b/c.txt").touch() raises FileNotFoundError if a/b/ does not exist, so call path.parent.mkdir(parents=True, exist_ok=True) first.
Touching many files with glob patterns
Atomic creation and race conditions
Checking if not path.exists() and then creating the file is not atomic: another process could create or delete the file in between. Path.touch(exist_ok=True) avoids that check and is safe for most use cases.
Comparing the approaches
Permission errors on existing files
On an existing file, Path.touch() first calls os.utime(path, None) and only falls back to opening the file (with O_CREAT | O_WRONLY) if that call fails. A file you cannot update timestamps on, for example one owned by another user, can therefore still raise PermissionError.
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
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.