Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switching the contents of one directory to another with Python

I have 2 folders, let’s call them dir1 and dir2.
Is there a simple way to move all files from dir1 to dir2 and vice-versa?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would use a third temporary folder:

from pathlib import Path
import shutil

def move_files(src_path, trg_path):
    for src_file in Path(src_path).glob('*.*'):
        shutil.copy(src_file, trg_path)

move_files('/path/to/dir1/', '/path/to/tmp/')
move_files('/path/to/dir2/', '/path/to/dir1/')
move_files('/path/to/tmp/', '/path/to/dir2/')

You need a temporary folder because there could be files that have the same name. The temporary folder must be empty.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading