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
