Copy File and Rename in Python

Python – Copy File and Rename

To copy a file from one location to another, and rename the file in destination directory, use shutil Python library. shutil.copy(source, target) copies the source file to the file path specified by target.

The syntax to use shutil.copy() function is

import shutil

shutil.copy(source, target)

where source and target are absolute, or relative file paths.

Examples

In the following example, we will copy the file at location a/b/sample.txt to c/d/new_sample.txt.

Python Program

import shutil

source = 'a/b/sample.txt'
target = 'c/d/new_sample.txt'

shutil.copy(source, target)

Summary

In this tutorial of Python Examples, we learned how to copy a file from one location to another, and renaming the file during copying to destination.