Find and move specific words in filenames

Question:

i have the following problem, there are files with the following names: 1234_43v5_2ws4.bsw.3r5_3d5_9z5 here is only the .bsw. is important everything else is subject to change.

There is a main folder, e.g. C:/Data/Main; in the Main folder there are different folders that have different names and in there also are different folders that have different names but they have the xxx_xxx.bsw.xxx_xxx files that I need.

How can i find the different .bsw. files and move this to the target folder.

Ive tryed this one

source_dir= pathlib.Path('C:/Data/Main/')
target_dir= pathlib.Path('C:/Data/bswdata')

for p in source_dir.glob('*.bsw.*'):
    shutil.move(p, target_dir / p.name)

The Code is running without Issues but the files are not moved .. is there a problem with the some folders?

Asked By: INegativeI

||

Answers:

Firstly try to find where the error is coming and whats its cause by using any suitable exception handeling method like:

Method 1: You can check using print statement if program is itirating through file and attempting them to move like:

for p in source_dir.glob('*.bsw.*'):
    print(f"Moving {p} to {target_dir / p.name}")
    shutil.move(p, target_dir / p.name)

Method 2: or you can better use try and except to know why the files are not being moved and correct your code accordingly like :

import shutil
import pathlib

source_dir = pathlib.Path('C:/Data/Main/')

target_dir = pathlib.Path('C:/Data/bswdata')

try:

    for p in source_dir.glob('*.bsw.*'):

        print(f"Moving {p} to {target_dir / p.name}")

        shutil.move(p, target_dir / p.name)

except Exception as e:

    print(f"An error occurred: {e}")
Answered By: Mridul Gupta

Your glob pattern isn’t searching the subdirectories that contain the files. From pathlib.Path.glob

Patterns are the same as for fnmatch, with the addition of “**” which
means “this directory and all subdirectories, recursively”. In other
words, it enables recursive globbing

for p in source_dir.glob('**/*.bsw.*'):
    shutil.move(p, target_dir / p.name)
Answered By: tdelaney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.