Sub topic 11
Renaming, Deleting, and Reading File Metadata with pathlib
This chapter covers the Path methods that change or describe things that already exist on disk: renaming and moving, deleting, and reading metadata such as size and modification time. It assumes you can build Path objects, check whether they exist, and read and write files with read_text and write_text. It also assumes you know basic try/except.
Unlike the path-building methods in earlier chapters, the methods here touch the file system. They can fail, and some cannot be undone.
Renaming and moving with rename and replace
Path.rename(target) renames the file or directory at the path to target. Since Python 3.8 it returns a new Path for the target. The original Path object is not changed, so it still points at the old location.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
src = base / "draft.txt"
src.write_text("v1\n", encoding="utf-8")
new = src.rename(base / "final.txt")
print(new.name) # final.txt
print(src.exists()) # False
print(src.name) # draft.txt (the old object is unchanged)
print(new.read_text(encoding="utf-8"), end="") # v1The same method moves an item to another directory, as long as the target is the full new path, including the file name. Passing a directory as the target does not mean "put it inside". The target must be the final path.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
report = base / "report.csv"
report.write_text("a,b\n", encoding="utf-8")
archive = base / "archive"
archive.mkdir()
moved = report.rename(archive / report.name)
print(moved.relative_to(base)) # archive/report.csv on POSIXrename versus replace
The two methods differ when the target already exists.
| Situation | `rename` | `replace` |
|---|---|---|
| Target file does not exist | Renames | Renames |
| Target file exists, POSIX | Silently overwrites it | Silently overwrites it |
| Target file exists, Windows | Raises `FileExistsError` | Silently overwrites it |
| Target is a non-empty directory | Raises `OSError` | Raises `OSError` |
| Source does not exist | Raises `FileNotFoundError` | Raises `FileNotFoundError` |
Because rename behaves differently by platform, use replace when you want overwriting and check exists() first when you do not. If you must not overwrite, remember that the check and the rename are two separate steps. Another process can create the target between them.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
a = base / "a.txt"
b = base / "b.txt"
a.write_text("new\n", encoding="utf-8")
b.write_text("old\n", encoding="utf-8")
a.replace(b)
print(b.read_text(encoding="utf-8"), end="") # new
print(a.exists()) # Falsereplace is also the basis of a safe-write pattern. Write the full content to a temporary file in the same directory, then replace the real file with it. Readers see either the old file or the new one, never a half-written file. The two paths must be on the same file system for this to work.
Moves across file systems
rename asks the operating system to change a name. That cannot work if the target is on a different disk or mount, and it raises OSError. For that case, use shutil.move(src, dst). It tries a rename first and falls back to copy-then-delete. It accepts Path objects and returns the destination. Copying is shutil.copy2, not a Path method in most supported Python versions.
Deleting files and directories
pathlib has two deletion methods, and each handles only one kind of item.
Path.unlink()removes a file or a symbolic link. It removes the link itself, not the file the link points to.Path.rmdir()removes a directory, and only if it is empty.
unlink(missing_ok=True) (Python 3.8+) ignores a missing file instead of raising FileNotFoundError. That makes cleanup code idempotent: running it twice does no harm.
from pathlib import Path
import shutil
import tempfile
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
cache = base / "cache"
cache.mkdir()
(cache / "one.tmp").write_text("1", encoding="utf-8")
(cache / "missing.tmp").unlink(missing_ok=True) # no error
try:
cache.rmdir()
except OSError as exc:
print("rmdir failed:", type(exc).__name__) # OSError
(cache / "one.tmp").unlink()
cache.rmdir()
print(cache.exists()) # False
tree = base / "tree" / "deep"
tree.mkdir(parents=True)
(tree / "x.txt").write_text("x", encoding="utf-8")
shutil.rmtree(base / "tree")
print((base / "tree").exists()) # FalseThere is no Path method that deletes a whole tree. shutil.rmtree does it, and it is permanent. Nothing goes to a recycle bin.
Calling unlink() on a directory fails. The exception is IsADirectoryError on Linux and PermissionError on Windows and macOS, so catch OSError if you need portable handling.
Check first, or just try?
Code like if p.exists(): p.unlink() has a race. Another process can delete the file between the two calls, and unlink then raises anyway. Prefer attempting the operation and handling the failure, or use missing_ok=True, which does the check atomically.
Reading file metadata
Path.stat() returns an os.stat_result object with the metadata the operating system keeps for the item. The fields you will use most are:
st_size: size in bytes. For directories the value is system-dependent and not meaningful.st_mtime: last modification time, as seconds since the Unix epoch (a float).st_atime: last access time. Many systems update it lazily or not at all.st_ctime: metadata change time on Unix, but creation time on Windows. Do not treat it as "created" on portable code.st_mode: type and permission bits.
from datetime import datetime, timezone
from pathlib import Path
import stat
import tempfile
with tempfile.TemporaryDirectory() as tmp:
f = Path(tmp) / "data.bin"
f.write_bytes(b"\x00" * 2048)
info = f.stat()
print(info.st_size) # 2048
modified = datetime.fromtimestamp(info.st_mtime, tz=timezone.utc)
print(modified.isoformat()) # e.g. 2026-11-26T11:51:57.046000+00:00
print(stat.S_ISREG(info.st_mode)) # True
print(stat.S_ISDIR(info.st_mode)) # False
print(stat.filemode(info.st_mode)) # e.g. -rw-r--r--Pass tz= when you convert timestamps. Without it you get a naive local time that is easy to compare wrongly with other data.
stat() raises FileNotFoundError for a missing path. It also follows symbolic links by default, so it describes the target. Use Path.lstat(), or stat(follow_symlinks=False) on Python 3.10+, to describe the link itself.
Two helpers cover permissions and ownership on POSIX systems:
Path.chmod(mode)changes permission bits, for examplep.chmod(0o600). On Windows it affects little beyond the read-only flag.Path.owner()andPath.group()return names and are not available on Windows.
Updating times with touch
Path.touch() creates an empty file if none exists, or updates the modification time if one does. With exist_ok=False it raises FileExistsError when the file already exists.
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
marker = Path(tmp) / ".last_run"
marker.touch()
first = marker.stat().st_mtime
marker.touch()
second = marker.stat().st_mtime
print(second >= first) # TrueMarker files like this are a simple way to record "when did this job last run" and to compare against other files' st_mtime values.
Common failure modes
- Wrong relative target. A relative argument to
renameis resolved against the working directory. Build the target from the source'sparent. - Moving into a directory.
file.rename(directory)does not place the file inside the directory. It fails or, worse, replaces something. Usedirectory / file.name. - Cross-device moves.
renameraisesOSErroracross mounts. Useshutil.move. - Open files on Windows. Renaming or deleting a file that another process holds open raises
PermissionError. POSIX systems allow it. - Check-then-act races. Handle exceptions instead of testing
exists()first. - Time zones.
fromtimestampwithouttzreturns local naive time. - Coarse timestamps. Some file systems store modification times at 1 to 2 second resolution, so two writes close together can show equal
st_mtime.
Exercise
You run Path("logs/app.log").rename("app.log.1") from the directory /srv. Where does the file end up, and what should you write to rename it in place?
Show answer
The file moves to /srv/app.log.1, because the relative target is resolved against the current working directory, not the source's directory. To rename in place, use src = Path("logs/app.log") and src.rename(src.with_name("app.log.1")). The result is logs/app.log.1.
Exercise
Why is if p.exists(): p.unlink() weaker than p.unlink(missing_ok=True), and what does rmdir() do when the directory still holds a file?
Show answer
Between the exists() check and the unlink() call another process can remove the file, so unlink() still raises FileNotFoundError. missing_ok=True makes the missing-file case a no-op in a single step. rmdir() raises OSError for a non-empty directory. To delete a directory and everything in it, use shutil.rmtree.
Exercise
A script compares Path("a.txt").stat().st_ctime across Linux and Windows to decide which file was created first. Why is this unreliable, and which field is safe for "last modified"?
Show answer
On Unix st_ctime is the time of the last metadata change, such as a rename or a permission change. On Windows it is the creation time, so the same code means different things on each system. The portable field for last modification is st_mtime.