match filenames to foldernames then move files

python, regex

Solution

You do not need regular expressions for this.

How about something like this:

import glob
files = glob.glob('*.txt')
for file in files:
    # this will remove the .txt extension and keep the "aN" 
    first_part = file[:-4]
    # find the matching directory
    dir = glob.glob('%s_*/' % first_part)[0]
    os.rename(file, os.path.join(dir, file))

Problem

I have files named "a1.txt", "a2.txt", "a3.txt", "a4.txt", "a5.txt" and so on. Then I have folders named "a1_1998", "a2_1999", "a3_2000", "a4_2001", "a5_2002" and so on. I would like to make the conection between file "a1.txt" & folder "a1_1998" for example. (I'm guessing I'll need a regular expresion to do this). then use shutil to move file "a1.txt" into folder "a1_1998", file "a2.txt" into folder "a2_1999" etc.... I've started like this but I'm stuck because of my lack of understanding of regular expresions. ``` import re ##list files and folders r = re.compile('^a(?P') m = r.match('a') m.group('id') ## ##Move files to folders ``` I modified the answer below slightly to use shutil to move the files, did the trick!! ``` import shutil import os import glob files = glob.glob(r'C:\Wam\*.txt') for file in files: # this will remove the .txt extension and keep the "aN" first_part = file[7:-4] # find the matching directory dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0] shutil.move(file, dir) ```

Original source