File renaming changes the path used to refer to a file or directory. In Python, call `Path.rename(destination)` on the existing path. A destination in the same directory changes its name; a destination in another directory also moves it. section 12.4.1
Change a filename
`Path('README.md.old').rename(Path('README.md'))` changes the visible filename from `README.md.old` to `README.md`. section 12.4.1
For a batch of files:
- Find the source paths with `glob()` or `rglob()`; filter them when needed, such as by extension or symlink status. section 12.6.2 section 20.2
- Create the destination directory before renaming. `mkdir(exist_ok=True)` permits an existing directory. section 12.6.2
- Build each destination path, then call `source.rename(destination)`. For example, `file.rename(backup_dir / file.name)` puts a file in `backup` under its current filename. section 12.6.2
Listing 20.1 File files_01.py
import datetime
import pathlib
FILE_PATTERN = "*.txt" #1
ARCHIVE = "archive"
def main():
date_string = datetime.date.today().strftime("%Y-%m-%d") #2
cur_path = pathlib.Path(".")
archive_path = cur_path.joinpath(ARCHIVE)
archive_path.mkdir(exist_ok=True) #3
paths = cur_path.glob(FILE_PATTERN)
for path in paths:
new_filename = f"{path.stem}_{date_string}{path.suffix}"
new_path = archive_path.joinpath(
new_filename) #4
path.rename(new_path) #5
if __name__ == '__main__':
main()
This complete script finds `*.txt` files, inserts today's date between each filename's stem and suffix, creates an archive directory, and renames each file into it. section 20.2
`os.rename(source, destination)` offers a function-based alternative; use `os.path.join()` to assemble its path strings. Renaming is distinct from deletion: `Path.unlink()` deletes a file, while `Path.rmdir()` removes an empty directory. A short archiving script is a starting point, not a plan for every naming or file-management problem. section 12.6.2 section 12.4.1 section 20.2
