How to Move Files From One Directory to Another Using Python


If you need to move files from one directory to another directory, using Python, then you can do one of the following:

Option 1 – Using shutil.move()

import shutil
import os
 
file_source = 'source/directory'
file_destination = 'destination/directory'
 
get_files = os.listdir(file_source)
 
for file in get_files:
    shutil.move(file_source + file, file_destination)

Option 2 – Using os.replace()

import os
 
file_source = 'source/directory'
file_destination = 'destination/directory'
 
get_files = os.listdir(file_source)
 
for file in get_files:
    os.replace(file_source + file, file_destination + file)

Option 3 – Using pathlib

from pathlib import Path
import shutil
import os

file_source ='source/directory'
file_destination ='destination/directory'

for file in Path(file_source).glob('some_file.txt'):
    shutil.move(os.path.join(file_source,file), file_destination)