liveBook · Manning

File renaming

As explained in The Quick Python Book, Fourth Edition

rename is a filesystem path operation that changes a file or directory name and can relocate it when the destination path differs.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through Path.rename calls and batch scripts, while leaving more complex archiving requirements for later.
Examples
Shows a README filename change, a backup move for .test files, and a date-stamped text-file archive.
What it assumes
Assumes basic Python scripting and teaches the filesystem-specific steps through Path objects and small examples.
What you can do after
Apply it via pathlib to rename individual paths or move selected files into a prepared archive directory.
How it connects
Connects renaming to pathlib, glob patterns, path construction, directory creation, symlinks, and os.rename.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.