0

I currently have a parent directory with 10 folders with 10 different dates for names (ie. 2016-11-21, etc.) In these date folders, are WAV files with unique file names.

Separately, I have corresponding TXT files with the same name, but they are not currently in the folders with the matching WAV files. How can I loop it such that if the filenames match, the TXT file gets moved to the existing folder location within the parent directory?

Currently I have this structure:

/Folder1/File1.TXT
/Folder1/2011-11-21/File1.WAV

I want something such that the structure will become:

/Folder1/2011-11-21/File1.TXT
/Folder1/2011-11-21/File1.WAV

Is this possible? Thanks

  • Welcome to Super User! Please note that superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How do I ask a good question?. – DavidPostill Nov 22 '16 at 9:52
0

You can use glob and shutil to accomplish your task.

Note that WAV and TXT are case sensitive so you'll need to change accordingly, or add in something to check for both.

import os
import glob
import shutil

# Create a list of WAV files.  If you put in txt directory, remove Folder1; otherwise, put full path.
wav_files = glob.glob('Folder1/**/*.WAV')

# Create a list of text files to move
txt_files = glob.glob('Folder1/*.TXT')

# Check OS for file separator since that is not provided
if os.name == 'nt':
    separator = '\\'
else: 
    separator = '/'

for txt in txt_files:
    # [-1] takes the last part of the path
    # .strip removes .TXT from the file name 
    txt_name = txt.split(separator)[-1].strip('.TXT')
    for  wav in wav_files:
        wav_name = wav.split(separator)[-1].strip('.WAV')
        wav_path = wav.strip(txt_name + '.WAV')
        # Check if the wav_name and txt_name are the same.  
        # There is no check for case.    
        if wav_name == txt_name:
            shutil.move(txt, wav_path)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.