Python
Touch Interface
Programming
Software Development
User Interaction

Implement touch using Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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.

python
1from pathlib import Path
2
3# Create file if it doesn't exist, update timestamps if it does
4Path("myfile.txt").touch()
5
6# Create with specific permissions (Unix only)
7Path("myfile.txt").touch(mode=0o644)
8
9# Fail if file doesn't exist (exist_ok=False)
10try:
11    Path("newfile.txt").touch(exist_ok=False)
12except FileExistsError:
13    print("File already exists")
14
15# Touch multiple files
16for name in ["file1.txt", "file2.txt", "file3.txt"]:
17    Path(name).touch()
18
19# Create file in a nested directory (directory must exist)
20Path("logs/2025/output.log").touch()

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

python
1import os
2import time
3
4def touch(filepath):
5    """Mimic Unix touch command using os module."""
6    if os.path.exists(filepath):
7        # Update access and modification times to now
8        os.utime(filepath, None)
9    else:
10        # Create the file
11        open(filepath, 'a').close()
12
13touch("myfile.txt")
python
1import os
2
3# One-liner: open in append mode and close immediately
4# Creates file if missing, does not truncate if exists
5open("myfile.txt", 'a').close()
6
7# Update timestamps to current time
8os.utime("myfile.txt")

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

python
1import os
2import time
3from datetime import datetime
4
5# Set modification time to a specific date
6target_time = datetime(2025, 1, 15, 12, 0, 0).timestamp()
7os.utime("myfile.txt", (target_time, target_time))  # (atime, mtime)
8
9# Set only modification time, keep access time
10stat = os.stat("myfile.txt")
11os.utime("myfile.txt", (stat.st_atime, target_time))
12
13# Verify the timestamps
14stat = os.stat("myfile.txt")
15print(f"Access time:  {datetime.fromtimestamp(stat.st_atime)}")
16print(f"Modify time:  {datetime.fromtimestamp(stat.st_mtime)}")

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

python
1import os
2from pathlib import Path
3from datetime import datetime
4
5def touch(filepath, times=None, create=True, mode=0o666):
6    """
7    Full implementation of Unix touch.
8
9    Args:
10        filepath: Path to the file
11        times: Tuple of (atime, mtime) as floats, or None for current time
12        create: If True, create file if it doesn't exist
13        mode: File permissions for newly created files
14    """
15    path = Path(filepath)
16
17    if not path.exists():
18        if create:
19            # Create parent directories if needed
20            path.parent.mkdir(parents=True, exist_ok=True)
21            path.touch(mode=mode)
22        else:
23            return  # touch -c behavior: don't create
24
25    # Update timestamps
26    os.utime(filepath, times)
27
28# Usage examples
29touch("output.log")                                    # Create or update
30touch("output.log", create=False)                      # Update only (touch -c)
31touch("deep/nested/dir/file.txt")                      # Create with parents
32touch("file.txt", times=(1700000000, 1700000000))      # Specific timestamps

Batch Touch with Glob Patterns

python
1from pathlib import Path
2import os
3
4# Touch all .py files in a directory
5for pyfile in Path("src").glob("**/*.py"):
6    pyfile.touch()
7
8# Touch all files matching a pattern
9for logfile in Path("/var/log").glob("*.log"):
10    os.utime(logfile)
11
12# Create a set of files from a list
13filenames = ["README.md", "setup.py", "requirements.txt", ".gitignore"]
14for name in filenames:
15    Path(name).touch()

Context Manager for Safe File Creation

python
1from pathlib import Path
2import os
3import tempfile
4
5# Atomic touch: create temp file then rename
6def atomic_touch(filepath):
7    """Create file atomically to avoid race conditions."""
8    path = Path(filepath)
9    fd, tmp_path = tempfile.mkstemp(dir=path.parent)
10    os.close(fd)
11    os.rename(tmp_path, filepath)
12
13# Check-then-create has a race condition
14# (another process could create the file between check and create)
15# Path.touch() with exist_ok=True is safe for most use cases

Comparing Approaches

python
1from pathlib import Path
2import os
3
4filepath = "test.txt"
5
6# Method 1: pathlib (recommended, Python 3.4+)
7Path(filepath).touch()
8
9# Method 2: open + close (Python 2 compatible)
10open(filepath, 'a').close()
11
12# Method 3: os.utime (update only, file must exist)
13os.utime(filepath)
14
15# Method 4: os.open with flags (low-level control)
16fd = os.open(filepath, os.O_CREAT | os.O_WRONLY, 0o644)
17os.close(fd)
18os.utime(filepath)

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 mimicking touch to preserve existing file content.
  • Not closing the file handle: open(path, 'a') without .close() leaks a file descriptor. Use open(path, 'a').close() or a with statement. 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() raises FileNotFoundError if a/b/ does not exist. Call path.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 raises PermissionError. Use os.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. Use Path.touch(exist_ok=True) which handles this atomically.

Summary

  • Use Path("file.txt").touch() for the simplest Pythonic equivalent of Unix touch
  • 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.