Python Forum

Full Version: Move Files based on partial Match
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to move files to folders having same name or having part of the file name. I have 60000 files, in the folder (D:/Source) . , there names look like 5000.pdf, 5000..pdf, 5000...pdf till 30000. I want to move all files containing 5000 in its name to the folder D:/Destination/5000. I tried the below script generated by ChatGPT, but does not work.

import os
import shutil

source_folder = "D:\Source"
destination_folder = "D:\Destination"

for filename in os.listdir(source_folder):
source_file = os.path.join(source_folder, filename)
if os.path.isfile(source_file) and destination_folder in filename:
shutil.move(source_file, os.path.join(destination_folder, filename))
That's the trouble with AI, it requires a detailed description of the problem. The required level of detail is such that describing the program often takes more time than writing the program.

I think your approach is too limiting. You may as well make this a useful tool that you can use for moving other groups of files. Make a program that copies files matching a pattern to the specified directory. Something like "python copy.py pattern folder" where pattern would be something like "5000*.pdf". But wait, this is what the XCOPY command does in windows. Do you need to write a program at all? If XCOPY doesn't do it for you, take a look at robocopy.
Use Code tags.
Your description most have been basic and leaving out the 5000 part.
An other problem if don't know Python,then it can be hard to fix or suggest a update from ChatGPT.

Something like this and using pathlib
from pathlib import Path
import shutil

dir_find = '5000'
source_folder = Path("G:/div_code/Source")
des_folder = Path("G:/div_code")
des_subfolder = des_folder / dir_find
for file in source_folder.glob(f"{dir_find}*"):
    # Create the des subfolder if it doesn't exist
    des_subfolder.mkdir(parents=True, exist_ok=True)
    des_file = des_subfolder / file.name
    # move file can also use .copy
    shutil.move(file, des_file)