Python
Touch Interface
Programming
Software Development
User Interaction

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()

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 already exists (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()

With exist_ok=True (the default), touch() silently updates timestamps on existing files or creates new empty ones.

Using the os module

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")

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

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, 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:

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

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

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()

Atomic creation and race conditions

python
1import os
2
3# Atomic create: O_EXCL makes the check and the create one operation
4def atomic_touch(filepath):
5    """Create file atomically; raises FileExistsError if it exists."""
6    fd = os.open(filepath, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
7    os.close(fd)
8
9# Check-then-create has a race condition
10# (another process could create the file between check and create)
11# Path.touch() with exist_ok=True is safe for most use cases

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

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)

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.


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
Basis Lab
No 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 course
Data 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.

Practice algorithms