Copy File or Directory with pathlib Module in Python 3.14

Copy File or Directory with pathlib Module in Python 3.14

Working with files and directories is a common task of many Python applications. Traditionally, copying files or entire directory trees relied on the shutil module. While effective, this approach often felt inconsistent when the rest of the codebase already used pathlib.Path objects. Developers had to switch between object-oriented paths and function-based utilities. Since Python 3.14, the native copy operation has been added directly to Path.

Before Python 3.14, copying required shutil, even if paths were already represented as Path instances. This meant passing paths into standalone functions instead of calling methods on the objects themselves.

from pathlib import Path
import shutil

src = Path('old.txt')
dst = Path('new.txt')
shutil.copy2(src, dst) # or shutil.copy if no need to preserve file metadata

src = Path('old_dir')
dst = Path('new_dir')
shutil.copytree(src, dst)

Since Python 3.14, we can use the copy method directly on the Path object. This method duplicates a file or an entire directory tree and returns a new Path pointing to the copied location. If the source is a file and the destination already exists, it will be overwritten. We can also choose whether to keep file metadata such as timestamps and permissions.

from pathlib import Path

src = Path('old.txt')
dst = Path('new.txt')
src.copy(dst, preserve_metadata=True)

src = Path('old_dir')
dst = Path('new_dir')
src.copy(dst, preserve_metadata=True)

Since Python 3.14, we can also use the copy_into method, which is designed for copying a file or directory into an existing directory. Unlike copy, the destination must already exist and must be a directory.

from pathlib import Path

src = Path('test.txt')
dst = Path('my_dir')
new_path = src.copy_into(dst, preserve_metadata=True)
print(new_path) # my_dir/test.txt

src = Path('test_dir')
dst = Path('my_dir')
new_path = src.copy_into(dst, preserve_metadata=True)
print(new_path) # my_dir/test_dir

By performing copy operations directly on Path instances, the code stays concise, easier to understand, and consistently object-oriented - without the need to bring in additional modules.

Leave a Comment

Cancel reply

Your email address will not be published.