liveBook · Manning

Os.rename

As explained in The Quick Python Book, Fourth Edition

os.rename is an os-module function that changes a file or directory's pathname and can thereby move it.

Use `os.rename(source, destination)` to change a file or directory’s pathname. A destination in the same directory renames it; a destination in another directory moves it. section 12.4

os.rename('README.md', 'README.md.old')
os.listdir(os.curdir)
 
['anscombe.json',
 'README.md.old',
 '1.tmp',
 '2.tmp',
 'a.tmp',
 'california_housing_train.csv',
 'california_housing_test.csv',
 'mnist_test.csv',
 'mnist_train_small.csv']

Renaming `README.md` to `README.md.old` changes the name shown by `os.listdir`. section 12.4

For a move into a backup directory, create the directory first with `os.makedirs`, then pass the file’s current path and its intended backup path to `os.rename`. Build paths with `os.path.join` rather than relying on a file’s name alone. section 12.6.2

import os
 
cur_path = "."
new_path = os.path.join(cur_path,"backup")
 
# create backup directory
os.makedirs(new_path, exist_ok=True)                        #1
size = 0
for root, dirs, files in os.walk(os.curdir):
    for file in files:
        test_path = os.path.join(root, file)
        print(test_path)
 
        if (not os.path.islink(test_path) 
          and os.path.splitext(test_path)[-1] == ".test"):
            print(os.path.join(root, file))
            size += os.path.getsize(test_path)
            os.rename(test_path, os.path.join(new_path, 
                       os.path.basename(test_path)))        #2
print(f"{size}")

This script walks subdirectories, selects non-symlink `.test` files, totals their sizes, and moves them into `backup` with `os.rename`. section 12.6.2

For the same backup task, `shutil.move` is another option. With `pathlib` paths, `Path.rename` provides a corresponding operation; choose the interface that fits the rest of the code. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates two-path calls and a worked backup script; does not address rename failure cases or platform behavior.
Examples
Shows `README.md` becoming `README.md.old` and non-symlink `.test` files moving into `backup`.
What it assumes
Assumes familiarity with basic Python calls and filesystem paths; supplies concrete calls rather than teaching those fundamentals.
What you can do after
Apply it via Python’s `os` module to rename a pathname or move selected files into a prepared directory.
How it connects
Connects pathname construction and directory traversal to `os.makedirs`, `shutil.move`, and `Path.rename`.

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.