Sub topic 11
Renaming, deleting, and reading file metadata
This chapter assumes you can build Path objects, check them with exists(), is_file() and is_dir(), and create directories with mkdir. Here you will change what is on disk: move files, remove them, and read facts about them such as size and modification time.
Renaming and moving
Path.rename(target) moves a file or directory to target. On POSIX systems it silently overwrites an existing file at the target. On Windows it raises FileExistsError. Path.replace(target) always overwrites an existing file, on every platform. Both return a new Path for the target in Python 3.8 and later.
from pathlib import Path
work = Path("work")
work.mkdir(exist_ok=True)
draft = work / "draft.txt"
draft.write_text("first version\n", encoding="utf-8")
final = draft.rename(work / "final.txt")
print(final) # work/final.txt
print(draft.exists()) # FalseThe original draft object still holds the old path. Use the returned value for later work.
rename and replace do not create missing parent directories. They also can fail across file systems. If you move between disks, use shutil.move instead.
Deleting
Each kind of removal has its own method.
| Method | Removes | Fails when |
|---|---|---|
| `unlink()` | A file or symbolic link | The path is missing, unless `missing_ok=True` (Python 3.8+) |
| `rmdir()` | An empty directory | The directory is not empty or is missing |
from pathlib import Path
target = Path("work") / "final.txt"
target.unlink(missing_ok=True) # no error if already gone
Path("work").rmdir() # works only if work is emptypathlib has no method to delete a non-empty directory tree. Use shutil.rmtree(path) for that, and check the path first, because it cannot be undone.
Reading metadata with stat()
Path.stat() returns an os.stat_result object. Its most useful fields are:
st_size: size in bytes.st_mtime: last modification time, in seconds since the epoch.st_mode: file type and permission bits.
from datetime import datetime
from pathlib import Path
info = Path("metadata_demo.txt")
info.write_text("some content\n", encoding="utf-8")
st = info.stat()
print(st.st_size) # 13
print(datetime.fromtimestamp(st.st_mtime)) # for example 2026-11-26 12:02:58
print(oct(st.st_mode & 0o777)) # for example 0o644 on POSIXstat() raises FileNotFoundError if the path does not exist. It follows symbolic links, so you get facts about the target. Use lstat() to inspect the link itself.
Changing the modification time
The next sketch shows how the pieces fit together. A script checks whether a file is older than a limit and deletes it if so.
import time
from pathlib import Path
def remove_if_old(path: Path, max_age_seconds: float) -> bool:
try:
age = time.time() - path.stat().st_mtime
except FileNotFoundError:
return False
if age > max_age_seconds:
path.unlink(missing_ok=True)
return True
return False
sample = Path("old_file.tmp")
sample.write_text("x", encoding="utf-8")
print(remove_if_old(sample, 3600)) # False, the file is newThe function catches FileNotFoundError instead of calling exists() first. Another process could delete the file between the check and the use, so handling the error is the safer pattern.
Common errors
- Calling
rmdir()on a directory that still has files raisesOSError. Delete the contents first, or useshutil.rmtree. - Assuming
renamefails on every platform when the target exists. It overwrites on POSIX, so usereplacewhen you want overwriting and a pre-check when you do not. - Treating
st_mtimeas a date. It is a float number of seconds, so convert it withdatetime.fromtimestamp.
Exercise
You want to move a.txt to b.txt and be sure an existing b.txt is overwritten on both Windows and Linux. Which method do you call, and what does it return?
Show answer
Call Path("a.txt").replace("b.txt"). It overwrites an existing target on every platform and returns a new Path object for the target.
Exercise
Why does the remove_if_old function catch FileNotFoundError instead of checking path.exists() first?
Show answer
The file could be deleted by another process between the exists() check and the stat() call. Catching the error handles that case, while a prior check leaves a gap in which the call can still fail.