How to Move Files From One Directory to Another Using Python

0 min read 97 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags