Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use a replace-capable move or rename operation to move a file over an existing destination; do not delete the destination first. For important files, write or copy the new data to a temporary file in the destination directory, then replace the final path only after the temporary file is complete. The right API—and whether the operation is atomic or works across drives—depends on the language and filesystem.
Move, copy, rename, and overwrite: the difference
These terms describe related but different operations:
- Move or rename: changes a file’s path. The original path normally disappears.
- Copy: creates a second file and leaves the source in place.
- Replace: makes the destination path refer to the new file, superseding the old destination.
A move with replacement combines the first and third operations. It is not the same as opening the destination in write mode, which may truncate and modify that file in place. A replacement operation typically swaps which file the destination path refers to; it may not preserve the old file’s identity, permissions, or links.
Recommended Free Tools
Choose the operation that matches the job
| Need | Typical choice |
|---|---|
| Move one file over an existing file on the same filesystem | A replace-capable rename operation |
| Move files or directories, possibly between filesystems | A high-level move API that can copy and then delete |
| Keep the source until the replacement is verified | Copy to a temporary file, validate it, replace the destination, then remove the source |
| Publish a complete new configuration or report without exposing partial contents | Write to a temporary file in the destination directory, then replace the final path |
| Prevent accidental loss when names collide | Use a no-overwrite operation or choose a unique/versioned filename |
Why you should not delete the destination first
A sequence like “check whether the destination exists, delete it, then move the source” creates a gap in which the destination is gone. If the move then fails because of permissions, a missing source, or a device boundary, you have lost the old destination without successfully installing the new one.
#1 Best Overall
- Get NVMe solid state performance with up to 1050MB/s read and 1000MB/s write speeds in a portable, high-capacity drive(1) (Based on internal testing; performance may be lower depending on host device & other factors. 1MB=1,000,000 bytes.)
- Up to 3-meter drop protection and IP65 water and dust resistance mean this tough drive can take a beating(3) (Previously rated for 2-meter drop protection and IP55 rating. Now qualified for the higher, stated specs.)
- Use the handy carabiner loop to secure it to your belt loop or backpack for extra peace of mind.
- Help keep private content private with the included password protection featuring 256‐bit AES hardware encryption.(3)
- Easily manage files and automatically free up space with the SanDisk Memory Zone app.(5). Non-Operating Temperature -20°C to 85°C
It also creates a race: another process can create or change the destination after your existence check. Use one replace-capable operation when replacement is intended. An existence check is not synchronization.
Python
For a single file that must replace an existing file, use os.replace():
from pathlib import Path
import os
source = Path("source.txt")
destination = Path("archive/source.txt")
destination.parent.mkdir(parents=True, exist_ok=True)
os.replace(source, destination)
Python documents os.replace() as replacing an existing destination file when permitted. A successful rename is atomic on POSIX systems, but the operation can fail if source and destination are on different filesystems. Do not treat atomicity as a universal promise across every operating system, filesystem, or network share.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteDo not assume os.rename() has identical overwrite behavior everywhere. In particular, Python documents that it raises FileExistsError on Windows if the destination already exists; os.replace() is the clearer replacement API.
Use shutil.move() when you need a broader move that can handle directories or fall back across filesystems. On the same filesystem, Python uses a rename; otherwise, it copies the source to the destination and removes the source. Its overwrite behavior depends in part on the underlying rename semantics, so it is not the most explicit choice when replacing one file is the central requirement.
Rank #2
- Solid state performance with up to 800MB/s read speeds in a portable drive. (Based on internal testing; performance may be lower depending on host device, interface, usage conditions and other factors. 1MB=1,000,000 bytes.)
- Back up your content and memories on a storage solution that fits seamlessly into your mobile lifestyle.
- Take it with you on your adventures—up to two-meter drop protection means this durable drive can take a beating. (Based on internal testing.)
- Secure it to your belt loop or backpack for extra peace of mind thanks to the tough rubber hook.
- From Sandisk, a brand professional photographers trust to take on assignments.
Here is a basic error-handling pattern:
from pathlib import Path
import os
source = Path("source.txt")
destination = Path("archive/source.txt")
destination.parent.mkdir(parents=True, exist_ok=True)
try:
os.replace(source, destination)
except FileNotFoundError:
raise RuntimeError(f"Source or destination directory is missing: {source} -> {destination}")
except PermissionError:
raise RuntimeError(f"Permission denied while replacing: {destination}")
except OSError as error:
# Inspect error.errno for cases such as a cross-filesystem move.
raise RuntimeError(f"Could not replace {destination}: {error}") from error
If a move may cross filesystems, a copy-and-replace fallback can work, but treat it as a multi-step operation: copy to a temporary file in the destination directory, verify it if necessary, replace the final destination, and only then delete the source. Preserve or clean up temporary files deliberately if any step fails.
Publish a complete file with a temporary file
For generated configuration, state, indexes, or reports, do not copy directly over the final path if readers could encounter a partially written file. Write the complete replacement beside the destination, close it, then replace the destination path:
Free tools Windows power users keep installed
One-click scans. No signup required.
from pathlib import Path
import os
import tempfile
destination = Path("config.json")
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=destination.parent,
prefix=f".{destination.name}.",
delete=False,
) as temporary:
temporary.write('{"enabled": true}n')
temporary_path = Path(temporary.name)
try:
os.replace(temporary_path, destination)
finally:
temporary_path.unlink(missing_ok=True)
Remove the leading space before destination = Path(...) if copying this snippet into a Python file; it is shown here only as an indented code line? No: the code should be unindented. Here’s the corrected assignment line: destination = Path("config.json").
The temporary file belongs in the destination directory so the final replacement stays on the same filesystem. Atomic visibility means a reader sees the old file or the completed new file rather than an intermediate copy. It does not necessarily mean the new data will survive a sudden power loss: stronger durability requirements can involve flushing the file and its containing directory, with details varying by platform and filesystem.
Node.js
Node’s promise-based fs.rename() replaces an existing destination file, and rejects if the destination is a directory. See the Node.js documentation for fs.rename().
Rank #3
- Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
- Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
- To get set up, connect the portable hard drive to a computer for automatic recognition no software required
- This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
- The available storage capacity may vary.
import { promises as fs } from "node:fs";
try {
await fs.rename("source.txt", "destination.txt");
console.log("Moved and replaced successfully");
} catch (error) {
console.error("Move failed:", error);
}
The callback and synchronous forms are fs.rename(oldPath, newPath, callback) and fs.renameSync(oldPath, newPath). For a copy rather than a move, fs.copyFile() overwrites by default; pass fs.constants.COPYFILE_EXCL if the copy must fail when the destination exists. Node explicitly makes no atomicity guarantee for copyFile(), so do not use a direct copy as a safe-publication strategy. See the fs.copyFile() documentation.
Java
Use Files.move() with StandardCopyOption.REPLACE_EXISTING:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
Path source = Path.of("source.txt");
Path destination = Path.of("destination.txt");
Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
If you need an atomic move and the filesystem provider supports it, request ATOMIC_MOVE as well:
Files.move(
temporaryFile,
destination,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING
);
ATOMIC_MOVE is a request, not a guarantee that every provider can meet. The Java Files.move() documentation describes provider-specific behavior and the distinction between replacement and atomicity. Without the atomic option, a check for an existing target and the move need not form one atomic action.
Go
Go’s os.Rename() replaces an existing destination when it is not a directory, subject to operating-system restrictions:
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Rank #4
- NEARLY 2X FASTER THAN OUR PREVIOUS GENERATION(8) – move 1,000 high-res photos in under 60 seconds(6) with up to 2000MB/s transfer speeds(2).
- IP65 RATING AND UP TO 3M DROP PROTECTION(3) – protects against spills and drops.
- POCKET-SIZED – fits easily in pockets and small bags.
- SPACE TO OWN YOUR AI CONTENT – speed and capacity to download your high-res clips and photo edits.
- 256-BIT AES ENCRYPTION(4) – helps keep private files secure with password protection.
package main
import (
"fmt"
"os"
)
func main() {
if err := os.Rename("source.txt", "destination.txt"); err != nil {
fmt.Println("move failed:", err)
return
}
fmt.Println("moved and replaced successfully")
}
Consult the os.Rename() documentation for platform-specific limitations. In particular, do not assume identical atomicity across non-Unix systems, that an open destination can be replaced, or that a rename can cross volumes.
Unix-like shell commands
In Unix-like shells, mv -f source.txt destination.txt requests replacement without prompting, subject to permissions and filesystem rules. Use mv -i source.txt destination.txt when you want an interactive prompt instead. These are shell commands, not language-neutral APIs; do not assume the same flags or behavior in Windows PowerShell or every command environment.
Same filesystem versus another drive or mount
A same-filesystem rename is usually fast because it changes directory metadata rather than copying file contents. A cross-filesystem move cannot generally use one rename operation. Higher-level functions may instead copy the data and then remove the source, which takes longer and can fail partway through.
For a cross-filesystem move where the destination must be safely replaced:
- Create a uniquely named temporary file in the destination directory.
- Copy the source into it, preserving any required metadata deliberately.
- Close and, if needed, flush the file. Verify its size or checksum when correctness warrants it.
- Replace the final destination with the completed temporary file.
- Delete the source only after replacement succeeds.
- On failure, retain the source and decide whether to remove or quarantine the temporary file.
This avoids deleting the source before the destination is ready, but it is not a transaction spanning two filesystems. Ensure there is enough free space for the copy.
Best Value
- Easily store and access 5TB of content on the go with the Seagate portable drive, a USB external hard Drive
- Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
- To get set up, connect the portable hard drive to a computer for automatic recognition software required
- This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
- The available storage capacity may vary.
Common errors and practical fixes
| What you see | Likely cause | What to do |
|---|---|---|
| Source not found | Wrong path or the source was already moved | Validate the source path and log the paths used by the operation. |
| Destination parent missing | The target directory does not exist | Create it deliberately with the required permissions before moving. |
| “File exists” | The selected API does not replace by default | Use the language’s replacement option or replace-capable API. |
| Permission denied or file in use | Insufficient permissions, an incompatible open handle, or a sharing restriction | Check directory and file permissions, close handles where possible, and identify the process holding the file. Retry only for known transient errors, with a bounded retry policy. |
| Destination is a directory | The operation expects a file path, or the API interprets a directory as a container | Supply the complete destination filename and decide separately how directory contents should be handled. |
| Cross-device or cross-volume error | The rename cannot cross filesystem boundaries | Use a copy-to-temporary-file, replace, then delete sequence. |
| Disk full or interrupted copy | A cross-filesystem fallback could not finish | Keep the source, remove or quarantine the incomplete temporary file, and retry after resolving storage constraints. |
| Invalid name or path | The path violates platform rules or contains unexpected input | Validate paths according to the target platform and avoid trusting unvalidated filenames. |
Edge cases worth checking
Open files and file locks
Open-file behavior is operating-system dependent. Unix-like systems commonly allow a rename of an open file; existing readers may continue using the old file while new opens resolve to the replacement. Windows often refuses a replacement when another process has an incompatible handle. Close files you control, and check for editors, antivirus tools, indexers, or other processes holding a file. Do not blindly retry permission errors.
Directories
Replacing a file is not the same as replacing or merging a directory tree. Many APIs reject a destination directory, especially a non-empty one. Specify the intended full destination path rather than relying on an API to infer the filename.
Symbolic links and security
Decide whether your program intends to replace a symbolic link itself or operate on a path reached through a link. In privileged code, an untrusted symlink or writable parent directory can redirect operations unexpectedly. Restrict writable directories, validate ownership and permissions, avoid building paths from untrusted names, and use directory-relative APIs where available. Python’s os.replace() supports directory-descriptor-relative parameters on platforms that provide them.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Metadata and hard links
Replacement may change permissions, ownership, ACLs, extended attributes, timestamps, file IDs, hard-link relationships, or Windows alternate data streams. Copy APIs do not necessarily preserve all metadata. Python notes that even higher-level copy functions cannot copy everything; see its copy documentation. If those attributes matter, explicitly preserve and test them on the target system.
Same path and case-only renames
If source and destination might refer to the same file, detect or handle that case rather than assuming a rename will produce the intended result. In Python, os.path.samefile(source, destination) can compare existing paths on supported filesystems, but it can fail if a path does not exist. Case-only renames can also behave differently on case-insensitive filesystems; test the target platform and use an intermediate name if needed.
Network shares and crashes
Network filesystems may have different locking, rename, and durability behavior from a local disk. Test the actual storage environment. Also distinguish a successful path replacement from crash durability: for high-value data, use the platform’s documented flushing and recovery mechanisms, and keep a backup or versioned copy if loss would be unacceptable.
Quick Recap
Quick reference
| Environment | Replace-capable operation | Important qualification |
|---|---|---|
| Python | os.replace(source, destination) |
Can fail across filesystems; prefer over os.rename() for explicit replacement. |
| Node.js | fs.promises.rename(source, destination) |
Replaces a destination file; copying is a separate operation. |
| Java | Files.move(source, destination, REPLACE_EXISTING) |
Request ATOMIC_MOVE separately if supported and needed. |
| Go | os.Rename(source, destination) |
Platform and filesystem restrictions apply. |
| Unix-like shell | mv -f source destination |
Shell behavior is not universal across operating systems. |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

