Moving all files from one directory to another using Python

malina picture malina · Jan 24, 2017 · Viewed 97.4k times · Source

I want to move all text files from one folder to another folder using Python. I found this code:

import os, shutil, glob

dst = '/path/to/dir/Caches/com.apple.Safari/WebKitCache/Version\ 4/Blobs '
try:
    os.makedirs(/path/to/dir/Tumblr/Uploads) # create destination directory, if needed (similar to mkdir -p)
except OSError:
    # The directory already existed, nothing to do
    pass

for txt_file in glob.iglob('*.txt'):
    shutil.copy2(txt_file, dst)

I would want it to move all the files in the Blob folder. I am not getting an error, but it is also not moving the files.

Answer

Shivkumar kondi picture Shivkumar kondi · Jan 24, 2017

Try this:

import shutil
import os
    
source_dir = '/path/to/source_folder'
target_dir = '/path/to/dest_folder'
    
file_names = os.listdir(source_dir)
    
for file_name in file_names:
    shutil.move(os.path.join(source_dir, file_name), target_dir)