Move Files Matching specific pattern
Here we are trying to move all files having name patterns *_A_* to our destination directory. Using glob module in Python, we can easily do this in a single line, by defining a pattern for the file name.
Python3
import os import glob import shutil source = '/home/tuhingfg/Documents/source' destination = '/home/tuhingfg/Documents/destination' # # gather all files allfiles = glob.glob(os.path.join(source, '*_A_*' ), recursive = True ) print ( "Files to move" , allfiles) # iterate on all files to move them to destination folder for file_path in allfiles: dst_path = os.path.join(destination, os.path.basename(file_path)) shutil.move(file_path, dst_path) print (f "Moved {file_path} -> {dst_path}" ) |
Output:
Files to move ['/home/tuhingfg/Documents/source/type_A_4.txt', '/home/tuhingfg/Documents/source/type_A_5.txt', '/home/tuhingfg/Documents/source/type_A_2.txt', '/home/tuhingfg/Documents/source/type_A_3.txt'] Moved /home/tuhingfg/Documents/source/type_A_4.txt -> /home/tuhingfg/Documents/destination/type_A_4.txt Moved /home/tuhingfg/Documents/source/type_A_5.txt -> /home/tuhingfg/Documents/destination/type_A_5.txt Moved /home/tuhingfg/Documents/source/type_A_2.txt -> /home/tuhingfg/Documents/destination/type_A_2.txt Moved /home/tuhingfg/Documents/source/type_A_3.txt -> /home/tuhingfg/Documents/destination/type_A_3.txt
Destination folder after executing script:
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let’s see how to move a file in Python:
This can be done in two ways:
- Using os module.
- Using shutil module.