Python : How to move a file from the original location to the target location using shutil

You may use the following template to move a file.

import shutil

original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be moved\file name.file extension'

shutil.move(original, target)


Move a directory:

import shutil

original = r'original path where the directory is currently stored\directory name'
target = r'target path where the directory will be moved\directory name'

shutil.move(original, target)


Let’s now review some examples in Python.

Steps to move a File in Python.

Move the File

import shutil

original = r'original path where the file is currently stored\file name.file extension'
target = r'target path where the file will be moved\file name.file extension'

shutil.move(original, target)


For our example, the code to move the CSV file from the original location (i.e., Test_1) is as follows:

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\my_csv_file.csv'
target = r'C:\Users\Ron\Desktop\Test_2\my_csv_file.csv'

shutil.move(original, target)


Move a Directory using Python oppress.

import shutil

original = r'original path where the directory is currently stored\directory name'
target = r'target path where the directory will be moved\directory name'

shutil.move(original, target)

Alternatively, you may move a directory using this template:

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\my_folder'
target = r'C:\Users\Ron\Desktop\Test_2\my_folder'

shutil.move(original, target)


The directory would now appear.

Rename the File when moving it .

For example, let’s suppose that a new JPG file is in the Test-1 folder (where the file name is image).The code below can then be used to move the file (with the original file name of ‘image‘) to the target location.

import shutil

original = r'C:\Users\Ron\Desktop\Test_1\image.jpg'
target = r'C:\Users\Ron\Desktop\Test_2\new_image.jpg'

shutil.move(original, target)


The file should now appear in the Test_2 folder.