Managing files and directories is a common task in Python programs. For a long time, developers leaned on the shutil module to move files or entire directory trees. While reliable, this approach mixed object-oriented pathlib code with function-based utilities, leading to slightly awkward workflows. Since Python 3.14, the native move operation has been added directly to pathlib.Path.
Before Python 3.14, even if you were already using pathlib, moving files or directories still required calling shutil.move. This meant converting paths into function arguments rather than working entirely with Path objects.
from pathlib import Path
import shutil
src = Path('old.txt')
dst = Path('new.txt')
shutil.move(src, dst)
src = Path('old_dir')
dst = Path('new_dir')
shutil.move(src, dst)
Since Python 3.14, we can use the move method directly on the Path object. The method returns a new Path instance pointing to the destination. If the target path does not exist, it will be created automatically. When both source and destination are files, the destination file is replaced.
from pathlib import Path
src = Path('old.txt')
dst = Path('new.txt')
src.move(dst)
src = Path('old_dir')
dst = Path('new_dir')
src.move(dst)
Since Python 3.14, we can also use the move_into method, which is designed specifically for placing a file or directory inside an existing directory. Unlike move, the move_into method expects the destination to already be a directory and always nests the source inside it.
from pathlib import Path
src = Path('test.txt')
dst = Path('my_dir')
new_path = src.move_into(dst)
print(new_path) # my_dir/test.txt
src = Path('test_dir')
dst = Path('my_dir')
new_path = src.move_into(dst)
print(new_path) # my_dir/test_dir
By moving files and directories directly from Path objects, code becomes cleaner, more readable, and fully object-oriented - no extra imports required.
Leave a Comment
Cancel reply