File Management
Computer Tips
Software Solutions
Troubleshooting
File Usage

Is there a way to check if a file is in use?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Yes, but the phrase “in use” is more ambiguous than it sounds. A file may be open by another process, locked for exclusive access, or merely unavailable for the specific operation you want to perform. Those are related questions, but they are not identical, and operating systems do not all treat them the same way.

Ask the Right Question First

People often compress several questions into one:

  • is some process holding the file open
  • can I acquire an exclusive lock on it
  • can I rename, overwrite, or delete it right now

On Windows, these often overlap because file-sharing rules are relatively strict. On Linux and macOS, files can be open while many operations still succeed, and locks are often advisory rather than mandatory.

That is why a universal true-or-false “file in use” check is often less useful than asking whether the operation you need can succeed.

Process Inspection Is Best for Diagnosis

If you are troubleshooting interactively, the most useful first step is usually finding which process has the file open.

Linux and macOS:

bash
lsof /path/to/file

Linux alternative:

bash
fuser -v /path/to/file

Windows with Sysinternals Handle:

powershell
handle.exe C:\path\to\file.txt

These tools are more informative than a plain boolean result because they show who is using the file.

Programmatic Lock Probes

If your application really needs to know whether it can obtain a lock, the practical approach is to attempt the lock instead of guessing.

python
1import os
2import platform
3
4
5def can_exclusive_lock(path: str) -> bool:
6    if not os.path.exists(path):
7        return True
8
9    if platform.system() == "Windows":
10        import msvcrt
11        with open(path, "a+b") as f:
12            try:
13                msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
14                msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
15                return True
16            except OSError:
17                return False
18    else:
19        import fcntl
20        with open(path, "a+b") as f:
21            try:
22                fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
23                fcntl.flock(f.fileno(), fcntl.LOCK_UN)
24                return True
25            except BlockingIOError:
26                return False

This tells you whether your process can get the lock you requested. It does not prove that no other process has the file open.

Avoid Check-Then-Act Races

A fragile pattern is:

  1. check whether the file is free
  2. write to it later

That is a race condition. Another process can grab or reopen the file between your check and your write.

For correctness, it is often better to perform the operation atomically or to write to a temporary file and then replace the target.

python
1from pathlib import Path
2import tempfile
3
4
5def atomic_write_text(path: str, content: str) -> None:
6    target = Path(path)
7    target.parent.mkdir(parents=True, exist_ok=True)
8
9    with tempfile.NamedTemporaryFile(
10        "w",
11        delete=False,
12        dir=target.parent,
13        encoding="utf-8",
14    ) as tmp:
15        tmp.write(content)
16        temp_name = tmp.name
17
18    Path(temp_name).replace(target)

This often solves the real problem better than trying to predict file usage in advance.

Retry Logic Is Often More Practical

In user-facing tools, the practical goal is often to tolerate a briefly busy file rather than to prove an abstract lock state.

python
1import time
2
3
4def retry_open(path: str, attempts: int = 5, delay: float = 0.5):
5    for attempt in range(1, attempts + 1):
6        try:
7            return open(path, "r+", encoding="utf-8")
8        except OSError:
9            if attempt == attempts:
10                raise
11            time.sleep(delay * attempt)

This does not eliminate platform differences, but it can produce a better user experience when another application holds the file only briefly.

Common Pitfalls

The most common mistake is treating “open” and “locked” as exactly the same state.

Another pitfall is relying on a check-then-act workflow for correctness. Even if the check succeeds, the state can change immediately afterward.

Developers also often assume Windows semantics apply unchanged on Linux or macOS. They do not.

Finally, trying to detect file usage is sometimes the wrong abstraction. If the real need is safe replacement, atomic write patterns are usually the stronger answer.

Summary

  • You can probe whether a file appears busy, but the meaning depends on platform semantics.
  • Process-inspection tools are usually the best first diagnostic step.
  • A lock attempt tells you whether your process can obtain a lock, not whether the file has no open handles.
  • For correctness, prefer atomic write and replace patterns over fragile pre-check logic.
  • In user-facing tools, combine diagnostics with bounded retries and clear errors.

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.