How to move all the files from one directory to another using Python


files = os.listdir(source)

for f in files:
    shutil.move(os.path.join(source, f), dist)

In Python the files are moved by listing them calling the OS module and moving them using shutil.


This example creates 2 variables with the source and destination directories. The application lists the file in the source directory using os.listdir. Then for each of the files, the name is concatenated to the source directory and the move method is called.

import shutil
import os

source = './source'
destination = './destination'

files = os.listdir(source)

for f in files:
    sourceFile = os.path.join( source, f)
    print( "Moving " + sourceFile + " to " + destination  )
    shutil.move(sourceFile, destination)

The output will be:

$ python
Moving ./source\New Text Document.txt to ./destination

The method os.path.join is called to create the full path of the source file, this way the code can run on windows or unix systems.



Recent Comments